Change the body elements overflow in a component - ReactJs

Viewed 63
  1. A component called "BasicSearch" is used on all pages.
  2. The search component should be displayed on full screen with a vertical scroll to see the contents with a close button on the right top corner.
  3. The search components have some default links to navigate to different pages.
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?

1 Answers

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>
  );
}
Related