vikas95prasad
vikas95prasad

Reputation: 1332

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.

Upvotes: 2

Views: 67

Answers (3)

jo_va
jo_va

Reputation: 13964

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.

Upvotes: 4

claud.io
claud.io

Reputation: 1953

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

Upvotes: 0

Michael George
Michael George

Reputation: 248

Try this

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

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

Upvotes: 0

Related Questions