I've spent the last few days trying to get my nested routes to work, and I have to say that I'm completely lost.
I'm trying to get the following functionality to work:
- Sidebar with several links. One of them leads to /banking.
- /banking by default renders component
{ BankingCards }inside a{ CardWrapper }. - When user clicks on the
<Link>of one of the 4 cards rendered by{ BankingCards }, I want to render the nested path inside of the same{ CardWrapper }.
In the code block below, you will notice I tried using a switch statement to dynamically assign a component to actionComponent. This seems to break the functionality in more ways than one.
Is it the approach that is wrong, or am I missing something about React Router components?
// Banking.js import CardWrapper from '../../Wrappers/CardWrapper/CardWrapper'; import BankingCards from './BankingCards/BankingCards'; import AddBank from './AddBank/AddBank'; import AddDebit from './AddDebit/AddDebit'; import AddCredit from './AddCredit/AddCredit'; import AddDirect from './AddDirect/AddDirect'; class Banking extends Component { state = {}; render() { const { match } = this.props; console.log(match.params); // let actionComponent; // switch (match.params.actionType) { // case 'add-bank': // actionComponent = AddBank; // break; // case 'add-debit': // actionComponent = AddDebit; // break; // case 'add-credit': // actionComponent = AddCredit; // break; // case 'add-direct': // actionComponent = AddDirect; // break; // default: // return null; // } return ( <div className={classes.Banking}> <h1 className={classes.mainHeader}>Banking</h1> <CardWrapper> <Switch> <Route exact path={`${match.path}`} component={BankingCards} /> <Route path={`${match.path}/:actionType`} component={actionComponent} /> </Switch> </CardWrapper> </div> ) } } and
// BankingCards.js const bankingCards = ({ match }) => { return ( <> <Card> <h1>Add Bank Account</h1> <Link to={`${match.url}/add-bank`}> <SVG src={iconPlus} className={classes.iconPlus} /> </Link> <h3>Manage accounts</h3> </Card> <Card> <h1>Add Debit Card</h1> <Link to={`${match.url}/add-debit`}> <SVG src={iconPlus} className={classes.iconPlus} /> </Link> <h3>Manage debit cards</h3> </Card> <Card> <h1>Add Credit Card</h1> <Link to={`${match.url}/add-credit`}> <SVG src={iconPlus} className={classes.iconPlus} /> </Link> <h3>Manage credit cards</h3> </Card> <Card> <h1>Add Direct Debit</h1> <Link to={`${match.url}/add-direct`}> <SVG src={iconPlus} className={classes.iconPlus} /> </Link> <h3>Manage direct debits</h3> </Card> </> ); };
console.log(match.params);?renderprop instead ofcomponent, you can do your switch case inside it