Search code examples
javascriptreactjsreact-routerreact-propsreact-dom

Using Router DOM with React.js TypeError: Cannot read property "name" of undefined


I am trying to implement the React Router on my React.js application but as soon as I added the Router to my program I started getting a weird error.

    ReactDOM.render(
  <BrowserRouter>
    <App />
    <Route path="/" component={Headline}></Route>
    <Route path="/economy" component={Economics}></Route>
  </BrowserRouter>,

This is where I am implementing my <Router> component in index.js. But for some reason as soon as I add this to my application, I get the error:

TypeError: Cannot read property 'name' of undefined

name is the parameter of one of my objects, userInput, that I am passing via props to my child component, "headline" from App.js

<Headline
          userInput={this.state.userInput}
          money={this.state.money}
          displayFakeNews={this.state.displayFakeNews}
          onPublish={this.handlePublish}
        />

Inside the headline.jsx file, I am calling a <button> tag with the text rendering {this.props.userInput.name} and it the error comes up.

As soon as I remove the <Router> component from the index.js file, everything starts working absolutely perfectly.

*Note - Yes I tried to put the <Router> component in my App.js as well. And no I did not forget to import it.


Solution

  • In your routes, you're declaring that the component to be rendered at route "/" is the Headline component, but you're not passing it any props. This means that whenever you visit the home page, the Headline component is likely trying to access unassigned properties.

    From your question, I assume that you already have the Headline component being rendered in your <App /> component, and in this file, it is actually being passed the necessary props. If its already being rendered there, you don't need to use the <Route /> outside of the <App />. It's not clear the functionality you're looking for or how you've written your <App /> component, but I think what you should keep in mind is that the syntax you're using doesn't pass any props to <Headline /> from the route. If you actually want to pass those props, change

    <Route path="/" component={Headline}></Route>
    

    to

    <Route path="/">
      <Headline
        userInput={this.state.userInput}
        money={this.state.money}
        displayFakeNews={this.state.displayFakeNews}
        onPublish={this.handlePublish}
      />
    </Route>
    

    Passing the component to be rendered as a child of the route, so that you can actually pass it props.

    Consult the React Router documentation for more information on how to use the <Route /> component.