eip56
eip56

Reputation: 73

React Redux Lifecycle Props

I am using react and redux for an web application I am building.

For the most part everyhthing is working just fine however I have one major issue when it comes to passing props from the parent.

I have a main component which connects to redux and obtains my store. I pass the props just fine:

{ this.props.children && React.cloneElement(
  this.props.children, 
    { 
      preset: this.state.preset,
      children: this.state.babies,
      child: this.state.currentChild,
      name: this.state.firstName,
    }
)} 

So my particular page gets this props. I then pass needed props to child components, however I cannot access the props on mount or any other lifecycle method that react provides. The only place they seem to be available is in the render method, and thats after running a undefined check:

let child = this.props.child;

if(child.birthdate != undefined) {
  // do stuff here
}

It looks like i receive undefined twice then props finally come in and I am able to work with them.

My question is what lifecycle component should i be accessing to format my data. I have ran all available methods in the docs to try to console.log and see where I am at but they all return empty. The only place I actually get the props in in the render.

My explanation is poor i know but any help would be appreciated.

-E

Upvotes: 0

Views: 948

Answers (1)

Shota
Shota

Reputation: 7330

componentWillReceiveProps lifecycle method should do a trick. You can get a prop that is incoming and format it there. After that you can set formatted data in component state and use it in your render method like this.

componentWillReceiveProps(nextProps) {
  this.setState({
    formattedBirthdate: nextProps.child.birthdate
  });
}

The second option will be to do the same in your constructor.

After that you can output your formattedBirthdate in render, like this:

this.state.formattedBirthdate && <div>{this.state.formattedBirthdate}</div>

Upvotes: 3

Related Questions