Search code examples
javascriptreactjsreduxtraversal

React get state/data of parent element when click on child element


I have a construct of a parent element li which contains a link, and a font-awesome i. When I click on the i I need to pass the parent's title (from redux state) to the function.

  1. Do I need to somehow traverse up the DOM tree to get it?
  2. Do I set the event handler differently?
  3. How do I access the parent's state when a child element is clicked?

    export default class DashContent extends React.Component {
      deleteBase(title) {
        this.props.dispatch(removeBase(title))
      }
    
      render() {
        const baseList = this.props.bases.map(base => (
          <li key={base.title} className="base">
            <Link to={base.title}>{base.title}</Link>
            <i className="fas fa-times" onClick={title => this.deleteBase(title)} />
          </li>
        ));
      }
    
      return (
        <ul>
          {baseList}
          <li>
            <AddBase />
          </li>
        </ul>
      )
    }
    

Solution

    1. No you don't need to traverse anything, you can pass it directly in the onClick
    2. Yes you need to change your onClick to be like this

      onClick={() => this.deleteBase(base.title)}
      

    Now in your deleteBase function, you have title being passed as an argument

    1. Your 3rd point doesn't make much sense, because you are in the same component, so there is only 1 local state, that both the parent element and the child element have access to. But that is not useful in your case, because the title you are trying to access is not in the local state nor the redux state, but just a property of the base object itself.