73390

Using props to seed initial state in react without using React.createClass

Question:

I want to seed my component state using data from my props like the example here: <a href="https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html" rel="nofollow">https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html</a>

getInitialState: function() { return {count: this.props.initialCount}; },

Look near the bottom where it says "However, it's not an anti-pattern if you make it clear that the prop is only seed data for the component's internally-controlled state:" That is exactly what I want to do.

This works great when using React.createClass, but I'd like to do this using ES6 classes if possible. But when using ES6 classes, initial state is provided as a static property on the class. If you try to implement getInitialState(), you'll get an error. This means that I don't get the opportunity to compute it after props are available. See the section titled "ES7+ Property Initializers" at <a href="https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#es7-property-initializers" rel="nofollow">https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#es7-property-initializers</a>

In that section, they provide an example where the initial state is computed similar to the old getInitialState method, by simple setting this.state in the constructor. However, when I tried this, this.props was not set yet.

I have searched for a lifecycle method for when the props are initially set for the first time so that I can set the state at that moment, but I can't find any such lifecycle method.

Must I use React.createClass or is there a way to seed my initialState when using ES6 classes extending React.Component?

Answer1:

Here is a sample class where you can get it working

class Sample extends React.Component { constructor(props, context) { super(props, context); // replacement for componentWillMount this.state = { stateKey: props.stateVal }; } render() { return ( <div>{this.state.stateKey}</div> ); } }

Answer2:

It turns out I wasn't passing arguments to super in my constructor which is why the props weren't available in the constructor. I just had to change this:

constructor() { super() ... }

into this:

constructor(...args) { super(...args) ... }

My question was very similar to <a href="https://stackoverflow.com/questions/30075828/how-to-assign-a-prop-value-to-a-state-in-react?rq=1" rel="nofollow">How to assign a prop value to a state in react</a> which is what tipped me off to my mistake, so this might be considered a duplicate.

Answer3:

class Sample extends React.Component { constructor(props, context) { super(props, context); this.state = { stateKey: '' }; } componentWillReceiveProps(){ this.setState({ stateKey:this.props.data }) render() { return ( <div>{this.state.stateKey}</div> ); }

}

Recommend

  • Webpack-dev-server and isomorphic react-node application
  • Print: Entry, “:CFBundleIdentifier”, Does Not Exist have tried most solutions
  • The symbol you provided is not a function
  • what is the purpose of “export as namespace foo”?
  • Guava how to copy all files from one directory to another
  • SQL - Select lowest values with group by and order by?
  • SqlCommand back up Database
  • Cypher - matching two different possible paths and return both
  • How can we prepend rows to a react native list-view?
  • blade.php method outputting it's result to the form
  • xcode don't localize specific strings
  • Why use database factory in asp.net mvc?
  • Can someone please explain to me in the most layman terms how to use EventArgs?
  • Django simple Captcha “No module named fields” error
  • Database structure design with variable amounts of fields
  • formatting the colorbar ticklabels with SymLogNorm normalization in matplotlib
  • req.body is undefined - nodejs
  • C# - Serializing and deserializing static member
  • How do I fake an specific browser client when using Java's Net library?
  • Bug in WPF DataGrid
  • How to get a value (ex: baseURL) in every Karate feature?
  • How to recover from a Spring Social ExpiredAuthorizationException
  • Incrementing object id automatically JS constructor (static method and variable)
  • ILMerge & Keep Assembly Name
  • sending/ receiving email in Java
  • Statically linking a C++ library to a C# process using CLI or any other way
  • Large data - storage and query
  • WOWZA + RTMP + HTML5 Playback?
  • How to delete a row from a dynamic generate table using jquery?
  • Proper way to use connect-multiparty with express.js?
  • python regex in pyparsing
  • Hits per day in Google Big Query
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Java static initializers and reflection
  • Linking SubReports Without LinkChild/LinkMaster
  • unknown Exception android
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Checking variable from a different class in C#
  • Observable and ngFor in Angular 2
  • Unable to use reactive element in my shiny app