Passing data from one Router (Component) to another

Viewed 180

Trying to pass data from <Route exact path="/" render={()=><Home addToCart={(book)=>{addToCart(book)}}/>}></Route> to <Route path="/cart" render={()=><Cart addToCart={cartItem}/>}></Route>

Problem:

  1. Cart (render={()=><Cart addToCart={cartItem}/>) receives null but not object I am trying to send

Have placed 'console.log...' to help with debugging, look in code

import React from 'react';
import classes from './Nav.module.css';
import { Route, NavLink, Switch } from 'react-router-dom';
import Home from '../Home/Home';
import Cart from '../Cart/Cart';

var cartItem = null;

let addToCart = (book)=>{
  cartItem = book;
  console.log('1. Displays the correct object', cartItem);
}
const nav = ()=>{
  return (
    <div>
      <div className={classes.MenuContainer}>
        <div className={classes.Menu}>
          <div><NavLink to="/">Home</NavLink></div>
          <div><NavLink to="/cart">Cart</NavLink></div>
        </div>
      </div>
      <Switch>
        <Route exact path="/" render={()=><Home addToCart={(book)=>{addToCart(book)}}/>}></Route>
        <Route path="/cart" render={()=><Cart addToCart={cartItem}/>}></Route>
        {console.log('2. Displays null', cartItem)}
      </Switch>
    </div>
  );
} 

export default nav;
2 Answers

Redux would be a great solution as mentioned above.

Another option is to have a parent component manage the state and then pass the state to both of it's children.

You need to use something like redux if you want to pass data between same-level React components.

Related