0

I'm using a class component as a parent for my functional components, using a useState hook while rendering the components with react-router crash the app, however, if the components are placed normally in the parent class component the app compiles fine.

[error][1] [1]: https://i.sstatic.net/E4lKn.png

this does NOT WORK:

import React, {Component, useState} from 'react';
import {Route, BrowserRouter as Router, Switch} from 'react-router-dom'

class App extends Component {
  render(){
    return (
      <Router>
        <Switch>
          <Route exact path='/' render={FrontPage}/>
       </Switch>
      </Router>
    );
  }
}

const FrontPage = () => {

  const [a, b] = useState('')

  return (
      <div> hello world </div>
  )
}

export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

this WORKS

import React, {Component, useState} from 'react';
//import {Route, BrowserRouter as Router, Switch} from 'react-router-dom'

class App extends Component {
  render(){
    return (
      <FrontPage/>
    );
  }
}

const FrontPage = () => {

  const [a, b] = useState('')

  return (
      <div> hello world </div>
  )
}

export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

2
  • What error do you get and where? Commented Jul 28, 2020 at 15:52
  • In your Route, try using the component prop instead of the render prop. component={FrontPage}. Commented Jul 28, 2020 at 15:53

1 Answer 1

1
<Route exact path='/' render={FrontPage}/>

That's not the correct way to use the render prop. If you just want to pass in a component, you can use the component prop as in:

<Route exact path='/' component={FrontPage}/>

If you want to use the render prop, you need to pass in a function:

<Route exact path='/' render={routeProps => <FrontPage {...routeProps} />}/>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.