This code works on Codepen: See https://codepen.io/pkshreeman/pen/YQNPKB?editors=0010 However I am trying to use this in my own 'create-react-app' and the error of 'no-restricted-globals' is trigged by event.target.id
. What is a workaround for this. How do you get id from 'this' in react other than using the event target?
const Elem = (props) =>{
return (<div>
<h1 onClick={props.clickon} id="GM"> Good Morning!
<br/>
{props.name} {props.last}
<br />
This is phase three</h1>
<button id="btn1" onClick={props.clickon}> {props.text} </button>
<button id="btn2" onClick={props.clickon}> Second Button </button>
</div>
);
};
class App extends React.Component{
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
var clickedId = event.target.id;
console.log(clickedId);
alert("It works! You clicked " + clickedId)
}
render(){
return (
<Elem name = 'paul' last='shreeman' clickon={this.handleClick} text='PushMe'/>
)
}
}
ReactDOM.render(
<App />, document.getElementById('root'))
It's strange that this even works in codepen -- it looks like you're using a global
event
property.The right way to do this is to get the event object from the
handleClick
function's first param:You might need to specify the event on the passing function I guess.
Try this if it works for you.