Reputation: 13185
I'm looking at a React/Redux example here:
http://redux.js.org/docs/basics/ExampleTodoList.html
And notice the following is never done:
const CommentForm = React.createClass({
render: function() {
return (
<div className="commentForm">
</div>
);
}
});
Instead arrow functions are used instead of classes.
const Todo = ({ onClick, completed, text }) => (
<li
onClick={onClick}
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
>
{text}
</li>
)
Why is this and when do you have to implement the render method?
Upvotes: 0
Views: 910
Reputation: 12966
Let's say we have a React component that uses a single prop to say hello to someone.
class Hello extends React.Component {
render() {
return (
<span>Hello, {this.props.name}</span>
);
}
}
As you can probably tell, this component doesn't need any internal state to function correctly. All it needs is a single prop in order to do its job. React allows us to define components like this as stateless functions, which simply return markup given some props.
function Hello(props) {
return <span>Hello, {props.name}</span>;
}
We can use the ES6 syntax to use an arrow function instead, which allows us to implicitly return the markup:
const Hello = (props) => (<span>Hello, {props.name}</span>);
Additionally, we can destructure the name prop given to the component:
const Hello = ({name}) => (<span>Hello, {name}</span>);
Which gives you a result similar to the component that you posted in your question.
Upvotes: 1
Reputation: 1593
Stateless Functions:
You may also define your React classes as a plain JavaScript function. using the new ES6 arrow syntax:
const Todo = ({ onClick, completed, text }) => (
<li
onClick={onClick}
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
>
{text}
</li>
)
This simplified component API is intended for components that are pure functions of their props. These components must not retain internal state, do not have backing instances, and do not have the component lifecycle methods. They are pure functional transforms of their input, with zero boilerplate.
However, you may still specify .propTypes and .defaultProps by setting them as properties on the function, just as you would set them on an ES6 class.
you can get more information from the below URL StateLess Function
section,
https://facebook.github.io/react/docs/reusable-components.html
Upvotes: 0