mightym
mightym

Reputation: 191

React Router List and Detail Route at the same time

I have an issue with react router 4. And I'm not sure if its solvable:

This is my application layout: enter image description here

Which basically works. But the problem is that whenever I hit /items/:id/ via the link on the left side it also matches /items. Which causes the link list in the sidebar to rerender. The solution would be to nest the routes. But this is not possible due to the interface/DOM. The left sidebar needs be independent of the item detail. And I need to split those up like:

<div>
  <div className={styles.sidebar}>
    <HeaderContainer />
    <Switch location={location}>
      <Route exact path="/" component={Homepage} />
      <Route path="/items" component={Items} />
    </Switch>
  </div>
  <div className={styles.content}>
    <Route path="/items/:id" component={ItemDetail} />
  </div>
</div>

Thanks a lot for your help in advance!

Upvotes: 4

Views: 1624

Answers (1)

Peter
Peter

Reputation: 4731

I had a similar layout and I used something like this

//App.jsx
<Router path="/" component={Page}>

//Page.jsx
<Layout>
  <MasterView>
  <DetailView>
</Layout>

//MasterView.jsx
componentDidMount() {
  const { dispatch } = this.props
  const data = await api.getData();
  dispatch(updateDetail(data));
}
connect()(MasterView)

// DetailView.jsx
import { connect } from 'react-redux';

render() {
  return <ul>{this.props.list.map((item) => <li>{item}</li>)}</ul>;
}

// map the props you need to redux state
const mapStateToProps = (state) => ({ list: state.data.list });
connect(mapStateToProps)(DetailView)

Upvotes: 1

Related Questions