1

I currently have a React Router problem with my ReactJS project. I have a page that renders a view, inside the view is a .map function, which maps over all users and places the "first_name" inside an <h4> tag. The map functions works correctly for all users.

I want to be able to click on the user's first_name and it navigates to a new route with the _id as a parameter. The new component that you are navigated to will receive the _id and I will search the DB for their _id.

The intended routes:

| URL                 | Components |
|---------------------|------------|
| `/`                 | `Main`     |
| `/platform`         | `Platform` |
| `/platform/:userID` | `Editor`   |

Currently I have 3 files, the routes.js which holds all of the ReactRouter config. The index.js holds the rendered list of users from the DB. And the editor.js file that will receive a user's _id in the URL.

// Routes.js
import Main from './components/main';
import Home from './components/home';
import Platform from './components/platform';
import Editor from './components/editor';

<Route name="home" path="/" component={Main}>
    <IndexRoute component={Home} />
    <Route name="platform" path="platform/" component={Platform}>
        <Route name="user" path="/:userId" handler={Editor} />
    </Route>
</Route>


// Platform.js
{users.map(({_id, first_name, last_name}, index)=>
    <div>
        <Link to="user" params={{userId: _id}}>
            <h4 style={{fontFamily: 'Raleway', color: '#498EE0'}}>{first_name} {last_name} : {_id}</h4>
        </Link>
        <hr />
    </div>
)}

You should be able to click on the Link and the params are added onto the URL.

Currently when I try this, it simple appends /user onto my URL, so it appears localhost:8080/user

1 Answer 1

1

You need to change to parameter like this -

<Link to={`/user/${_id}`}>
  <h4 style={{fontFamily: 'Raleway', color: '#498EE0'}}>{first_name} {last_name} : {_id}</h4>
</Link>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks that now works, however it comes up with an error in the console: Warning: Location did not match any routes
You need to change your route also - <Route name="user" path="user/:userId" handler={Editor} />
Or if you prefer you can keep it like - <Link to={'/${_id}'}> and might accept this answer
Thanks so much, I also found that I'd nested the routes incorrrectly, so when having changed that and the changes you suggested, it works just fine :)

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.