ocram
ocram

Reputation: 1434

Pass a function through React Router

I want to pass a function to a child component through React Router. I tried the following but it doesn't seem to work.

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

  render() {
    return (
      <div className="App">
          <div className="content">
          <div className="centered-wrapper">
            <Switch>
              <Route exact path="/" component={Welcome} />
              <Route path="/life" render={props => <Life sayHello = {this.sayHello()} />} />
            </Switch>
          </div>                
      </div>
    );
  }
}

export default App;

I wanted to call sayHello() in the Life component as follows:

<div className="hello">{ this.props.sayHello() } I'm <Link to="/life">Marco</Link>! Welcome to my hood.</div>

Upvotes: 17

Views: 14473

Answers (2)

salezica
salezica

Reputation: 76909

Instead of passing the function, you're calling it and passing the returned result as prop.

sayHello    // function object
sayHello()  // function call, evaluates to return

Remove the parenthesis:

render={props => <Life sayHello={this.sayHello} />}

In the future, take a look at any errors you see in the console and add them to your question. If you attempted to call sayHello in the Life component, surely you saw an error similar to this one:

Uncaught TypeError: undefined is not a function

With this information, you could've found the problem yourself, or made it clearer for anyone trying to help :)

Upvotes: 3

oklas
oklas

Reputation: 8220

Replace:

<Route path="/life" render={props => <Life sayHello = {this.sayHello()} />} />

with

<Route path="/life" render={props => <Life sayHello = {this.sayHello} />} />

The mistake props receive the result of call of sayHello() function instead of function itself.

Upvotes: 18

Related Questions