Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React | Using 'parentNode' correctly?

Let's say I have a series of static divs that create rows with a handful of children. One of those children has a click handler, which should fire an event specific to its parent div. The event needs to target the parent div because we're changing some styling only in the parent.

Am I correct in how I've targeted each child's parentNode, in my code below? (Basically, is this best practice?) Just curious.

Thanks!

class ClickExample  extends Component {
  handleClick = (e) => {
    const parentDiv = e.target.parentNode;
    parentDiv.classList.toggle('someClass');
  }
  render() {
    return (
      <div>
        <div>
          <h1 onClick={(e) => { this.handleClick(e) }}>Click Me!</h1>
        </div>
        <div>
          <h1 onClick={(e) => { this.handleClick(e) }}>No, Click Me!</h1>
        </div>
      </div>
    );
  }
}

export default ClickExample
like image 507
joehdodd Avatar asked Aug 10 '26 07:08

joehdodd


1 Answers

This approach is against React philosophy. You should define a component for this purpose. You should read a little bit more of React philosophy but the correct approach would be something like this:

class ClickableComponent extends React.Component {

    render() {
       return (
           <div onClick={this.props.onClick}>
               { this.props.children }
           </div>
       );
    }
}

class ClickExample extends React.Component {

  handleClick() {
      this.setState({
          active: null
      });
  }

  render() {
    return (
      <div>
        <div className={this.state.active === 1 ? 'someClass' : null}>
            <ClickableComponent onClick={() => this.setState({ active: 1 })}>
                ClickMe
            </ClickableComponent>            
        </div>
        <div className={this.state.active === 2 ? 'someOtherClass' : null}>
            <ClickableComponent onClick={() => this.setState({ active: 2 })}>
                No, ClickMe!
            </ClickableComponent>
          </div>
      </div>
    );
  }
}

export default ClickExample
like image 119
Javier Enríquez Avatar answered Aug 12 '26 22:08

Javier Enríquez