We are using nextjs and trying to change the styling on a button click with document.getElementById but the styling does n't change irrespective of whatever we do.
pages/index.js
function Index() {
function change(){
console.log('changing');
document.getElementById('navi').style.color='blue';
}
return (<Some test={change}> </Some>)
}
Now, there is another normal react-component outside pages directory and is as below.
function Some(prop){
return (<div id="navi">
<button onClick={prop.test}></button>
</div>);
}
Now, whenever we click on the button it is executing the change() function in index.js and prints the console.log as 'changing' but the document.getElementById never works.
Is there any specific reason for this, Please let us know.
you have to use of useRef instead of id and then on the onClick when you call prop.test you have to pass that ref as an argument like this:
function change(e){
e.current.style.color="blue"
}
const navi= useRef(null)
<div ref={navi}>
<button onClick={()=>prop.test(navi)}></button>
</div>