Reputation: 1953
I have JSON data
of cricket teams. The cricket app is basically CRUD web app where we can create new teams or delete existing team. I want to map
each of the sidebar routes
check this for example: https://reacttraining.com/react-router/web/example/sidebar and display data for each of the team if I click on a particular team.
I have gone through the react router docs but the routes are hard coded but if I have dynamic list of cricket teams in sidebar how can I display data of a particular team onclicking particular team (See screenshot).
Routes in docs are:
const routes = [
{
path: "/",
exact: true,
sidebar: () => <div>home!</div>,
main: () => <h2>Home</h2>
},
{
path: "/bubblegum",
sidebar: () => <div>bubblegum!</div>,
main: () => <h2>Bubblegum</h2>
},
{
path: "/shoelaces",
sidebar: () => <div>shoelaces!</div>,
main: () => <h2>Shoelaces</h2>
}
];
Screenshot:
Upvotes: 0
Views: 229
Reputation: 6368
In your routes file you can specify a route like this:
<Route path="/teams/:teamId component={TeamDetails} />
And then in TeamDetails Component, you can access the teamId like:
this.props.match.params.id
To have match in your props you have to use withRouter
.
You can use withRouter as follows:
import { withRouter } from 'react-router';
class TeamDetails extends React.Component {
.....
.....
}
export default withRouter(TeamDetails);
Update for OP's comment:
In your TeamDetails component:
import { withRouter } from 'react-router';
import { connect } from 'react-redux';
class TeamDetails extends Component {
componentWillMount() {
this.props.getTeam(this.props.match.params.id)
}
render() {
console.log(this.props.team);
return (......);
}
}
const mapStateToProps = state => ({
teams: state.teams.team,
});
const mapDispatchToProps = dispatch => ({
getTeams: teamId => dispatch(actions.getTeams(teamId)),
});
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(TeamDetails));
When your TeamDetails component loads you will call an action called getTeam which will inturn call api. And in your reducer you will set a state called team. That state (team) will be available to you as a prop in your component via connect helper.
Upvotes: 1