简体   繁体   中英

How can I dynamically add attributes to component in reactjs

I have a scenario in which I want to dynamically assign an attribute to my PrivateRoute component.

This is my component.

<PrivateRoute exact path="/" component={HomePage} />

Here I want something like this:

<PrivateRoute {localStorage.getItem('user') ? exact : '' } path="/" component={HomePage} />

If the localStorage.getItem('user') is true then only exact should be applied.

You could use the spread operator like this:

const exact = localStorage.getItem('user') ? { exact: true } : { };
<PrivateRoute {...exact} path="/" component={HomePage} />

If getItem() returns falsy then an empty object will be spread and no attribute will be set at all.

Try this

const user = localStorage.getItem('user');

user ? <PrivateRoute exact path="/" component={HomePage} /> 
     : <PrivateRoute path="/" component={HomePage} />

if you have an object obj={a:'something', b:'somethingelse'} , just pass it to the component like this:

<PrivateRoute exact path="/" component={HomePage} {...obj} />

So inside your component you can access to it by:

this.props.a, this.props.b etc etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM