Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically redirecting inside child component in React JS is not working

I am developing a web application using React JS. Now, I am trying to programmatically redirect to another route. I can redirect like this.

this.props.history.push('/event/${this.props.id}/edit');

But when I use that in the child component it is not working. This is my scenario. I have a parent component called, EventListComponent. Inside that component, I render another child component called EventWidgetComponent. I am redirecting in the child component. But this.props.history is always undefined when I use it in the child component. How can I fix it?

like image 620
Wai Yan Hein Avatar asked Dec 07 '22 14:12

Wai Yan Hein


2 Answers

This is happening because your child component doesn't have the access to history. Child component is receiving the props from parent component not from Router, that's why.

These are the possible ways to solve the issue:

1- Either pass a method from parent to child and do the redirecting part inside parent component. Call that method from child component for redirecting.

2- Use withRouter hoc and render the child component inside that, it will provide access of history to child component.

Like this:

import { withRouter } from 'react-router-dom'

// Child component here

class Child extends React.Component {
   // code
}

export default withRouter(Child)

Check this answer: Programmatically navigating in React-Router v4

3- Pass the reference of history to child in props:

<Child history={this.props.history} />
like image 106
Mayank Shukla Avatar answered Dec 11 '22 09:12

Mayank Shukla


You can pass the history prop down from the component you are giving to a Route to the child component if you want to use it there.

Example

class App extends React.Component {
  render() {
    return (
      <div>
        {/* ... */}
        <Route exact path="/" component={Parent} />
        {/* ... */}
      </div>
    );
  }
}

class Parent extends React.Component {
  render() {
    return (
      <div>
        <Child history={this.props.history} />
      </div>
    );
  }
}
like image 34
Tholle Avatar answered Dec 11 '22 09:12

Tholle