Reputation: 477
Currently I have a navbar component that stays at the top for all the pages except the home page. To achieve this I used conditional rendering using useEffect and useState where I check if the current URL is the home page or not.
Code:
const [ishome,setIsHome] = useState(false);
useEffect(function onFirstMount() {
function onLoad() {
const url= window.location.href;
if(url === "http://localhost:3000/home"){
setIsHome(true)
}
else{
setIsHome(false)
}
}
window.addEventListener("load", onLoad);
}, []);
return (
<div className="fullNav" style={{marginTop:ishome?"100vh":""}}>
But the problem with this is that everytime this page loads I can see the navbar at the top of the home page for a split second and then it goes down. I dont want it to be shown at the top of the homepage everytime the user clicks refresh.
Upvotes: 1
Views: 224
Reputation: 20626
You are checking your location in useEffect(with an empty dependency array). This essentially means you are checking it in componentDidMount. So that is after the first render. Probably that is why your styling
is applied later.
If you want it to happen as soon as it is rendered, why not call the function while setting state.
Something like this:
export default function App() {
const [ishome,setIsHome] = useState(function onLoad() {
const url= window.location.href;
if(url.indexOf("x")){
return 'true';
}
else{
return 'false';
}
});
useEffect(() => {
}, []);
return (
<button>{ishome}</button>
)
}
Upvotes: 0