Jhay
Jhay

Reputation: 77

React Dynamic Router

How can I make this dynamic? I currently have static routes but now I need an optional url parameters

What I want to achieve is to have 2 optional segments like so;

/users/{id}/{something}

'id' and 'something' are the optional parameters

when I just access /users, it'll go to users list

server.js

require('babel-register');

const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const { StaticRouter } = require('react-router-dom');
const lodash = require('lodash');
const fs = require('fs');
const baseTemplate = fs.readFileSync('./index.html');
const template = lodash.template(baseTemplate);
const App = require('../client/Root').default;
const port = 3000;

const server = express();

server.use('/public', express.static('./public'));

server.use(function (req, res) {
  const context = {};
  const body = ReactDOMServer.renderToString(
    React.createElement(
      StaticRouter, { location: req.url, context: context }, React.createElement(App)
    )
  );

  res.write(template({ content: body }));
  res.end();
})

server.listen(port, function () {
  console.log(`server running at port ${port}`)
});

in my react component

const Root = () => (
  <Provider store={store}>
    <Switch>
      <Route path='/users' exact component={Home}/>
    </Switch>
  </Provider>
)

Upvotes: 0

Views: 159

Answers (2)

canaan seaton
canaan seaton

Reputation: 6868

you can use the following pattern with react-router...

<Route path="/users/:id" component={SomeComponent} />

and then you will have access to the id in SomeComponent as this.props.match.id

Upvotes: 1

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

You can nest your routes.

const Root = () => (
  <Provider store={store}>
    <Switch>
      <Route path="/users" component={Home}>
        <IndexRoute component={YourDefaultComponent} />

        <Route path=":id/:something" component={YourOtherComponent} />
      </Route>
    </Switch>
  </Provider>
)

Upvotes: 0

Related Questions