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'))
To fix the 'No restricted globals' ESLint Error when developing a React app, we can add the // eslint-disable-next-line no-restricted-globals comment before the code that is causing the error. But the better solution is to put window before the variable that causes the error.
To use the addEventListener method in function components in React: Set the ref prop on the element. Use the current property on the ref to get access to the element. Add the event listener in the useEffect hook.
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:
handleClick(event) {
var clickedId = event.target.id;
console.log(clickedId);
alert("It works! You clicked " + clickedId)
}
You might need to specify the event on the passing function I guess.
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(event){
var clickedId = event.target.id;
console.log(clickedId);
alert("It works! You clicked " + clickedId)
}
render(){
return (
<Elem name = 'paul' last='shreeman' clickon={(event)=>this.handleClick(event)} text='PushMe'/>
)
}
}
ReactDOM.render(
<App />, document.getElementById('root'))
Try this if it works for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With