Luis
Luis

Reputation: 35

Unable to use react hooks with react-router-dom

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>

Upvotes: 0

Views: 53

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84982

<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} />}/>

Upvotes: 1

Related Questions