How to use arrow functions inside React.createClass

I want to use ES6 (ES2015) as much as possible for my small project. Now I want to use arrow functions with React.

// What I want let Text = React.createClass({ componentDidMount: () => { setInterval(this.updateCurrentTime, 1000); } } // What I have let Paragraph = React.createClass({ render: () => (<div className="MySuperTable"><Text name="Dodo" startDate={(new Date()).toString()} /></div>) }); let Text = React.createClass({ getInitialState: function () { return { currentTime: (new Date()).toString() } }, componentDidMount: function () { setInterval(this.updateCurrentTime, 1000); }, updateCurrentTime: function () { this.setState({ currentTime: (new Date()).toString() }); }, render: function () { return ( <div> <span>Hello my name is {this.props.name}</span> <span>And I was born on {this.props.startDate}</span> <span>And I now it {this.state.currentTime}</span> </div> ); } }); ReactDOM.render( <Paragraph/>, document.getElementById('container') ); 
  • What do I need to do to make this work?
  • As I understand it, this will be the object passed to createClass , is this correct?
  • How to associate it with a Text instance?

Thanks in advance.

+5
source share
2 answers

You can change your code with ES2015 as follows

 class Text extends React.Component { constructor() { super(); this.state = { currentTime: (new Date()).toString() }; } componentDidMount() { setInterval(() => this.updateCurrentTime(), 1000); } updateCurrentTime() { this.setState({ currentTime: (new Date()).toString() }); } render() { return <div> <span>Hello my name is { this.props.name }</span> <span>And i was born { this.props.startDate }</span> <span>And i now it { this.state.currentTime }</span> </div> } }; let Paragraph = () => { return <div className="MySuperTable"> <Text name="Dodo" startDate={ (new Date()).toString() } /> </div> }; 

Example

React - Reusable Components

+5
source

As you said, you wanted to use ES6 as much as possible. So, instead of using createClass, you can use "React.Component", you can find more details here .

And then, to use the arrow, you can use Babel, preset-2015.

+1
source

Source: https://habr.com/ru/post/1245302/


All Articles