I have a banner in my react app which I can close:
I persist this state in localStorage:
const [bannerShown, setBannerShown] = useState(true);
useEffect(() => {
const data = localStorage.getItem('MY_APP_STATE');
if (data !== null) {
setBannerShown(JSON.parse(data));
}
}, []);
useEffect(() => {
localStorage.setItem('MY_APP_STATE', JSON.stringify(bannerShown));
}, [bannerShown]);
{bannerShown && (<MyBanner onClick={() => setBannerShown(false)} />)}
This is working fine. Now I want to add a condition:
I only want to show the banner when it contains a certain query param:
import queryString from 'query-string';
const queryParams = queryString.parse(location.search);
const hasQueryParam = queryString
.stringify(queryParams)
.includes('foo=bar');
How do I combine above state and boolean (hasQueryParam
) in a clean way?
CodePudding user response:
You can chain together several statements in the JSX {bannerShown && hasQueryParam && (<MyBanner onClick={() => setBannerShown(false)} />)}
Or you could put this into an if statement
let showItem;
if (bannerShown && hasQueryParam) {
showItem = <MyBanner onClick={() => setBannerShown(false)} />
}
Then in the JSX {showItem}
CodePudding user response:
set state true if query-string has any value
useEffect(() => {
const foo = qs.parse(location.search);
console.log(foo)
if(!Object.keys(foo).length === 0){
setBanner(true)
}else{
setBanner(false)
}
}, [])