[React] How to pass props from NavBar to component?

Hello,
How can I pass props from Layout’s NavigationTop to children component (ClothesList)?
I want to pass currentTerm to {ClothesList} component.
Here is the link to my repo: CLICK

class App extends React.Component {
  render() {
    return (
      <React.Fragment>
        <Layout>
          <Switch>
            <Route component={ClothesList} path='/' exact />
            <Route component={Cart} path='/cart' />
          </Switch>
        </Layout>
      </React.Fragment>
    );
  }
}


class Layout extends Component {
  render() {
    return (
      <Fragment>
        <NavigationTop />
        {this.props.children}
        <NavigationBottom />
      </Fragment>
    );
  }
}



class NavigationTop extends React.Component {
  constructor(props) {
    super(props);
    this.state = { currentTerm: "t-shirts" };
  }

  render() {
    return (
      <div className={useStyles.root}>
        <AppBar position='static'>
          <Toolbar>
            <Box p={2}>
              <Button
                variant='contained'
                color='secondary'
                onClick={() => this.setState({ currentTerm: "t-shirts" })}
              >
                T-Shirts
              </Button>
            </Box>
            <Box p={2}>
              <Button
                variant='contained'
                color='secondary'
                onClick={() => this.setState({ currentTerm: "jeans" })}
              >
                Jeans
              </Button>
            </Box>
            <Box p={2}>
              <Button
                variant='contained'
                color='secondary'
                onClick={() => this.setState({ currentTerm: "shoes" })}
              >
                Shoes
              </Button>
            </Box>
          </Toolbar>
        </AppBar>
      </div>
    );
  }
}

You can pass them down to the children, but it will make it super complicated. You need them available so you can hand them to the Route component, like so:

<Route
  component={(routeProps) => <ClothesList foo={foo} bar={bar} {...routeProps} /> }
  path='/'
  exact
/>

(Passing routeProps is essential: it’s match, location and history)

So basically, you want whatever you want out of the nav to go up the tree then back down into the route to the component. Which is messy. So there is this, which in would negate having to pass through the router at all:

1 Like