17

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>

2 Answers 2

18

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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 :)

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.