aspirisen aspirisen - 10 days ago 6
React JSX Question

How to add new route dynamically?

Is it possible to add new route to router dynamically at runtime when the router has been initiated? For example user types something in input and after that I create a new route.

Answer

You probably want to use route params.

Here is a brief example:

import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, browserHistory, Link} from 'react-router';

class App extends React.Component {
  state = {
    value: '',
  }

  handleChange = (event) => {
    this.setState({
      value: event.target.value,
    });
  }

  render() {
    return (
      <div>
        <input type="text" value={this.state.value} onChange={this.handleChange} />
        <Link to={`/${this.state.value}`}>{this.state.value && `Go to /${this.state.value.toLowerCase()}`}</Link>
      </div>
    );
  }
}

const Page = (props) => (
  <h1>{props.params.term}</h1>
);

ReactDOM.render(
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="/:term" component={Page}/>
    </Route>
  </Router>,
  document.querySelector('#app'),
);