I'm working on a web App project and I have the following component that is returned by antd Menu
object.
const items = [
{
label: <Link to='/register'>Register</Link>,
key: 'register',
icon: <UserAddOutlined />,
style: { marginLeft: 1030}, // problem: hard-coded margin
},
{
label: <Link to='/login'>Login</Link>,
key: 'login',
icon: <UserOutlined />,
style: { marginLeft: 'auto'},
},
];
return <Menu mode="horizontal" items={items} />;
Now I have an object named user
. If user
is not null (which means there is a user who is logged in currently), I want to hide register
in the above items
object; otherwise I want to show register
in the Menu
. The Menu
component will be looked like:
Can anyone help me with that?
You can insert this code after declaring items
,
if(users!==null)
{
items.splice(0,1) //removes first array element which is the register button
}
I would highly recommend you to use state for this purpose because that is the intended way for such cases.
By that I mean encapsulate the items
object into a state and use the code above during every re-render using something like useeffect
hook
Look at the question and the verified answer below to understand how to do it in newer versions of react
how to update an object using useEffect in Reactjs and Typescript