Skip to content

Instantly share code, notes, and snippets.

@crshmk
Last active December 3, 2018 22:34
Show Gist options
  • Save crshmk/3cc11c5540a7df19030481a4a16189a0 to your computer and use it in GitHub Desktop.
Save crshmk/3cc11c5540a7df19030481a4a16189a0 to your computer and use it in GitHub Desktop.
nested react router 4

a route /docs/two/six renders:

<App>
  <a>one</a>  <a>two</a>  <a>three</a>
  
  <Outer>
    two 
    
    <a>four</a>  <a>five</a>  <a>six</a>
  
    <Inner>
    
      <p>6</p>

App makes links out of data.one, data.two & data.three -> 'one', 'two', and 'three'

Outer is passed either data.one, data.two, or data.three to props.topic based on the route param at docs/:topic

Outer also dynamically generates the sublinks, e.g. /docs/two would generate links 'four', 'five', and 'six'

Inner computes the needed value of stuff, e.g. /docs/two/six renders 6 in its <p> tag

let data = {
one: {links: ['one', 'two','three'], stuff: {one: 1, two: 2, three: 3} },
two: {links: ['four', 'five','six'], stuff: {four: 4, five: 5, six: 6} },
three: {links: ['seven', 'eight','nine'], stuff: {seven: 7, eight: 8, nine: 9} }
}
class App extends Component {
constructor(props) {
super(props)
}
render() {
let topLinks =
Object.keys(data)
.map(topic => <Link to={`/docs/${topic}`}>{topic}</Link>)
return (
<div>
<nav>{topLinks}</nav>
<Route
path="/docs/:topic/"
render={props => <Outer topic={props.match.params.topic} data={data} />}
/>
</div>
)
}
}
class Inner extends Component {
constructor(props) {
super(props)
}
render() {
return <p>{this.props.stuff[this.props.category]}</p>
}
}
class Outer extends Component {
constructor(props) {
super(props)
}
render() {
let topic = this.props.topic
let topicData = this.props.data[topic]
let links = topicData.links.map(l =>
<Link to={`/docs/${topic}/${l}`}>{l}</Link>
)
return (
<div>
<h3>{topic}</h3>
<nav>{links}</nav>
<Route
path="/docs/:topic/:category"
render={props =>
<Inner stuff={topicData.stuff} category={props.match.params.category}/>
} />
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment