2

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.