Hareesh
Hareesh

Reputation: 1587

How to get the event target inside the parent component in ReactJS

I have a Main component with code

changeColor = (color) => {

}

toggle = (e) => {
  console.log(e.target)
}

<div>
  <EditComponent changeColor={this.changeColor.bind(this)}>
  <TextComonent toggle={this.toggle.bind(this)}>
</div>

Edit component is

color = (value) => {
  this.props.changeColor(value)
}
<div>
  <button value='red' onClick={this.color.bind(this,"red")}>Red</button>
  <button value='blue' onClick={this.color.bind(this,"blue")}>Blue</button>
</div>

Text component is

toggle = (e) => {
  this.props.toggle(e)
}
<div>
  <p class="black-color" onClick={this.toggle.bind(this)}>Text 1</p>
  <p class="black-color" onClick={this.toggle.bind(this)}>Text 2</p>
</div>

I will be clicking on Text 1 or Text 2 first and I will get the event inside toggle function. Next I will click the button Red or Blue. Then I want to change the class to either red-color or blue-color for that particular Text that i have clicked before. How can I get the event inside the parent component to find the particular text or is there any other way to to this?

I want to get the event.target inside the Parent component. I got the event object in parent but event.target is null

Upvotes: 0

Views: 1089

Answers (3)

Hareesh
Hareesh

Reputation: 1587

I found the exact solution as to add event.persist(); to get the event.target inside parent component.

Upvotes: 0

Kishan Jaiswal
Kishan Jaiswal

Reputation: 664

<div>
 <EditComponent changeColor={this.changeColor.bind(this)}>
 <TextComonent toggle={this.toggle}>
 </div>

try this way dont bind function in parent component and try,you will get the target

Upvotes: 1

JavanPoirier
JavanPoirier

Reputation: 442

You are not using "bind" correctly. You don't need to bind with an anonymous function.

class Hello extends React.Component {
  render() {
    return (
    <div>
      <p onClick={(e) => this.toggle(e)}>
        Test
      </p>
    </div>);
  }

  toggle = (e) => {
    console.log(e.target.innerText);
    }
}

From the event variable in toggle, you can perform your changes as need be.

Upvotes: 0

Related Questions