Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 231
ocram Avatar asked May 22 '17 15:05

ocram


People also ask

How do I pass a component in react router?

If you are using react-router v4, you can pass it using the render prop. Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function children prop. It works exactly like render except that it gets called whether there is a match or not.


2 Answers

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.

like image 164
oklas Avatar answered Nov 26 '22 18:11

oklas


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

like image 20
slezica Avatar answered Nov 26 '22 17:11

slezica