Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router error (Failed prop type: Invalid prop `children` supplied to `Switch`, expected a ReactNode.)

Try to modify component, the main idea is, I want create login page, try modify App.js but get error

warning.js?6327:36 Warning: Failed prop type: Invalid prop children supplied to Switch, expected a ReactNode.

My code is:

class App extends Component {
  constructor(props) {
      super(props)


}

 routeWithSubRoutes(route) {
  return (
    <Route
      key={_.uniqueId()}
      exact={route.exact || false}
      path={route.path}
      render={props => (
        // Pass the sub-routes down to keep nesting
        <route.component {...props} routes={route.routes || null} />
      )}
    />
  );
 } 

 render () {
  return (
    <div className={styles.App}>
    <Helmet {...config.app} />
    <NavBar />
    <Switch>
      {routes.map(route => this.routeWithSubRoutes.bind(this,route))}
    </Switch>
    </div>
  )
 }



}

export default App;

Code that I try to modify

export default () => {
  // Use it when sub routes are added to any route it'll work

  const login = () => {

  }

  const routeWithSubRoutes = route => (
    <Route
      key={_.uniqueId()}
      exact={route.exact || false}
      path={route.path}
      render={props => (
        // Pass the sub-routes down to keep nesting
        <route.component {...props} routes={route.routes || null} />
      )}
    />
  );

  var isLogin = false;

  if(!isLogin) {
    return (
      <Login />
    )
  }

  if(isLogin) {
    return (
      <div className={styles.App}>
        <Helmet {...config.app} />
        <NavBar />
        <Switch>
          {routes.map(route => routeWithSubRoutes(route))}
        </Switch>
      </div>
    );
  }


};

this code is working, but my not, how to fix this?

like image 268
egorchik Avatar asked May 16 '26 05:05

egorchik


1 Answers

Function.bind doesn't call the function, it only binds its context. Instead, you should bind it in the constructur:

class App extends Component {
  constructor(props) {
    super(props)

    this.routeWithSubRoutes = this.routeWithSubRoutes.bind(this)
  }

  /* ... */

  render () {
    return (
      <div className={styles.App}>
        <Helmet {...config.app} />
        <NavBar />
        <Switch>
          {routes.map(route => this.routeWithSubRoutes(route))}
        </Switch>
      </div>
    )
  }
}
like image 56
TimoStaudinger Avatar answered May 17 '26 19:05

TimoStaudinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!