3

I just now observed that some of my component is having history and some do not have it. My component is comp1, comp2, comp3

comp1 is parent of comp2, comp2 is parent of comp3

comp1
|____comp2
     |_____comp3

Given all are stateful components. And access to comp1 is through routing.

My observations says that those component who are connected through routers directly have only the this.props.history available.

Q. Can any one throw some light here on this fact?

Q. Can we access history on remaining components?

Ladoo
  • 169
  • 7

1 Answers1

1

The components given to the component prop of a Route component will be given the route props. If you want a component deeper down in your app to have access to them as well, you can use the withRouter HOC.

Example

class Component3 extends React.Component {
  render () {
    console.log(this.props.history);

    return <h3> Test </h3>;
  }
}

export default withRouter(Component3);
Tholle
  • 83,208
  • 13
  • 152
  • 148
  • you mean if I pass my Component in withRouter, that HOC will return me a component that has history and some more key value pairs attached to it – Ladoo Jul 30 '18 at 20:15
  • @Ladoo That's right. It will give you the history object’s properties and the closest ``'s match – Tholle Jul 30 '18 at 20:17
  • 1
    thanx.. this is a new thing I learnt.. thanx for links too. But I used 'react-router-dom' for this – Ladoo Jul 30 '18 at 20:29