React – accessing DOM value of parent element


I have a React component that renders a grid like this :

for (let i=0; i<items.length; i++) {
    if (filterItem(items[i])) {
      rows.push(
        <div className="row" key={items[i]._id} id={items[i]._id} onClick={props.onClick}>
          {props.db !== "videos" && <div className="centered">{items[i].level}</div>}
          {props.db === "questions" && <div className="centered left">{items[i].question}</div>}
          {props.db !== "questions" &&  <div className="centered left">{items[i].instructions}</div>}
          <div className="centered" onClick={props.delete}><FontAwesomeIcon icon={ faTrashAlt }/></div>
        </div>
      );
    }
}

I display some items from different databases and depending on the database the fields are not the same.
I need to implement onClick handler which will either preview a video (in case of videos database is displayed) or get the id value of the grid row (in case of any other database is displayed)

My current code looks like this:

handleClick(e) {
    
    if (this.state.database === "videos") {
      this.setState(state => ({
        videoPreview: this.getDbItem(e.target.innerText).link
      }))
    }

    else if (e.target.parentElement.id) {
      this.editMode(e.target.parentElement.id) //get id of the row div

    }

}

and it works, but seems wrong…

Is there a better way to do this ?

Source: JavaSript – Stack Overflow

November 12, 2021
Category : News
Tags: javascript | onclick | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.