Route within list item


(Thord Lindé) #1

Hi
I want to render a route inside a list item inside the parent route component. When I click on the Link the li shall open and reveal the child component. I have modified a React Router example from React Training to do this. My question is if the solution I have come up with is a good and proper one. Or if there are smarter solutions.

This is how my Topics Component, where this happens, look:

class Topics extends Component {
  state = { open: false }

  handleClick = value => {
    this.setState({ open: value })
  }

  render () {
    const { match } = this.props
    const { open } = this.state
    return (
      <div>
        <h1>Topics</h1>
        <ul style={{ padding: '5px', listStyleType: 'none' }} >
          {topics.map(({ name, id }) => (
            <li style={{ border: 'solid green 2px', width: '300px', padding: '5px' }} key={id} 
              className={(open===id) ? 'open' : null}>
              <Link to={`${match.url}/${id}`} 
                onClick={() => this.handleClick(id)}>{name}</Link>
              <div>
                {
                  open===id ? <Route path={`${match.path}/:topicId`} render={({ match }) => (
                    <Topic
                      topic={topics.find(({ id }) => id === match.params.topicId)}
                      match={match}
                    />)}
                  /> : null
                }
              </div>
            </li>
          ))}
        </ul>
      </div>
    )
  }
}

The full code can be found at https://github.com/Thord/react-router-example