Pass the function through the React Router

I want to pass a function to a child component through a React Router. I tried the following, but it does not 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>
+4
source share
2 answers

Replace:

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

with

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

Error details receive the result of calling the function sayHello()instead of the function itself.

+3
source

Instead of passing a function, you call it and pass the return result as a support.

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

Remove the brackets:

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

In the future, review all the errors that you see in the console and add them to your question. If you tried to call sayHelloin the component Life, you probably saw an error similar to this:

Uncaught TypeError: undefined is not a function

, :)

+2

Source: https://habr.com/ru/post/1677700/


All Articles