React.useEffect(() => { document.body.style.position = "fixed"; }, []);
return (
<div className="container">
<Button onClick={() => { document.body.style.position = "relative"; }}> close </Button>
<a href="./xyz">Link1 </a>
<a href="./xyz-abc">Link2 </a>
</div>
);
The body element is set to position: relative when the close button is clicked. but, when the user navigates via any of the Link buttons then the body element is unchanged.
Could someone help me understand where I'm going wrong and how to fix this issue?
Make position state and add dependency to useEffect so that when its changes useEffect will change the body position to new position. And use Link tag of react-router-dom. Actually page reloads when you click on link using anchor tag so your position automatically set to its initial state:
const Search= ()=>{
const [position, setPosition] = useState("fixed"); // initially its fixed
React.useEffect(() => { document.body.style.position = position }, [position]);
return (
<div className="container">
<Button onClick={() => setPosition("relative")}> close </Button>
<Link to="/xyz">Link1 </Link>
<Link to="/xyz-abc">Link2 </Link>
</div>
);
}