Refactor a React component from function to class ES6

I am new to ES6. A little embarrassed in different ways to write a React component. I started with "React.createClass", then switched to "extends React.Component" with ES6 class syntax.

The following Redux tutorial now I see that they define components in this way.

import React, { PropTypes } from 'react' const Todo = ({ onClick, completed, text }) => ( <li onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }} > {text} </li> ) Todo.propTypes = { onClick: PropTypes.func.isRequired, completed: PropTypes.bool.isRequired, text: PropTypes.string.isRequired } export default Todo 

How can I reorganize this “function” into an ES6 class that extends React.component? I think the returned JSX is the render () method, right? What about onClick completed text arguments?

thanks

+5
source share
2 answers

For your component, it is best to make it a pure function, not an ES6 class, because it can display props as a function of it and does not support state. You can still use ES6 syntax (export, arrow functions, etc.).

Facebook’s explanation : “In an ideal world, most of your components will be stateless, because in the future they’ll be able to do the work of optimizing specific to these components as well, avoiding unnecessary checks and memory allocation. This is a recommended sample when possible.”

 import { PropTypes } from 'react' function Todo = (props) => ( <li onClick={props.onClick} style={{ textDecoration: props.completed ? 'line-through' : 'none' }} > {props.text} </li> ) Todo.propTypes = { onClick: PropTypes.func.isRequired, completed: PropTypes.bool.isRequired, text: PropTypes.string.isRequired } export default Todo 
+3
source

ES6 syntax equivalent:

 import React, { Component, PropTypes } from 'react' class Todo extends Component { render() { const { onClick, completed, text } = this.props return ( <li onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }} > {text} </li> ) } } Todo.propTypes = { onClick: PropTypes.func.isRequired, completed: PropTypes.bool.isRequired, text: PropTypes.string.isRequired } export default Todo 

If you use babel to convert your code, and you have class property properties , you can do the following:

 import React, { Component, PropTypes } from 'react' class Todo extends Component { static propTypes = { onClick: PropTypes.func.isRequired, completed: PropTypes.bool.isRequired, text: PropTypes.string.isRequired } render() { const { onClick, completed, text } = this.props return ( <li onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }} > {text} </li> ) } } export default Todo 

Just to be clear, this second example cannot be considered “standard ES6,” but I think the static properties are so clean that I thought it was worth showing this approach as well.

+4
source

All Articles