Conditional statement returns false every time, even if it "should" return true...
const Navy = () => {
const [content, setContent] = useState(<Today/>)
const homepage = () => {
setContent(<Today/>);
}
const accountpage = () => {
setContent(<Account/>);
}
return(
<Nav >
<ul className='menuItems'>
<div className='mainmenu'>
<Nav.Link className='linkitem' style={{color: content === useState(<Today/>) ? 'red' : 'blue'}}>
<li onClick={homepage}>
<i class="fa fa-home" aria-hidden="true"></i>
Home
<div className='arrow'>
<i class="fa fa-angle-double-right" ></i>
</div>
</li>
</Nav.Link>
<Nav.Link className='linkitem' style={{color: content === useState(<Today/>) ? 'red' : 'blue'}}>
<li onClick={accountpage}>
<i class="fa fa-cog" aria-hidden="true"></i>
Account
<div className='arrow'>
<i class="fa fa-angle-right"></i>
</div>
</li>
</Nav.Link>
</div>
<ul/>
</Nav>
)}
My goal is to make this line return true if the component is currently in use (currently returns false regardless):
<Nav.Link className='linkitem' style={{color: content === useState(<Today/>) ? 'red' : 'blue'}}>
CodePudding user response:
<Today />
is an istance of your Component: every time you call <Today />
you create a new, different, object. In any case, you should compare content
, not useState(content)
You can try a tricky (untested) solution like:
content.constructor.name === 'Today' ? ...
Else, you can change the state as a flag:
const [content, setContent] = useState('today')
then, the comparison sure works, and you can choose the render with:
content === 'today' ? <Today> : <Account>
But i suggest you a more clean solution with React router DOM.
And then:
const YourComponent = () => {
const location = useLocation();
...
return <>
// when you want to select color
matchPath(location, {path: '/today'}) ? 'color1' : 'color2'
// when you choose what component show
<Switch>
<Route exact path="/today">
<Today>
</Route>
<Route exact path="/account">
<Account>
</Route>
</Switch>
</>
CodePudding user response:
useState(something) always gives you an array containing 2 thing
- value
- updateFuncion
so you are comparing with value with an array containing [value, updateValueFunction]
Added a picture.
If you try to compare the content and useState()[0] you still will have some differences to the whole 2 objects.
So still you have to check are the two same check the content.type === useState()[0].type enter image description here