Answer the question
In order to leave comments, you need to log in
How to pass user data from store to React + React Router?
Good morning. There is such a question. I assumed we have a user repository (I note, without a back and, accordingly, without a database). For example userStorage.js :
const users = [
{
id: 1,
name: 'Every Interaction',
username: 'EveryInteract',
},
{
id: 2,
name: 'AppleInsider',
username: 'appleinsider',
},
];
...
import users from './userStorage';
...
<BrowserRouter>
<React.Fragment>
<Nav />
<Switch>
<Route path="/:user" component={Profile} />
<Redirect exact from="/" to="/EveryInteract" />
</Switch>
</React.Fragment>
</BrowserRouter>
<Route path="/:user" render={() => <Profile prop1 prop2 />} /> ?
Answer the question
In order to leave comments, you need to log in
(if react-router version 4)
You will have in this.props.match.params.user what the person entered after / for the route:
Therefore, in componentDidMount of the Profile component, if you need to "emulate" data loading, through setTiemout or just directly in the render component, you can use this ( ) value and that's it.
How you will get the user object from the data array is up to you. You can search in an array, you can make a method in the same file and export it, for example:
export function findUserById(id) => {
// ищем по id элемент в массиве и возвращаем его
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question