From example on official site:
First, if we want to build a Clock in the beginning, this how we tried to make a component that is object-oriented, maintainable factor with a stateless function object.
function Clock(props) {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {props.date.toLocaleTimeString()}.</h2>
</div>
);
}
function tick() {
ReactDOM.render(
<Clock date={new Date()} />,
document.getElementById('root')
);
}
setInterval(tick, 1000);
quote from doc
to make the Clock component truly reusable and encapsulated. It will
set up its own timer and update itself every second.
...
Ideally we want to write this once and have the Clock update itself...
So here is the spirit of React, we want to convert this function object to a class, which could maintain itself, so now we involve render()
in, more specifically we involve stateful component in:
Add a single empty method to it called render()
...
Clock is now defined as a class rather than a function.
Then we get:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
this.clockCore = this.clockCore.bind(this);
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
tick() {
this.setState({
date: new Date()
});
}
clockCore() {
return (<div>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>);
}
render() {
return this.clockCore();
}
}
As you known, render()
be triggered again an again if the state of component need to be refreshed by setState()
.
Update
In my opinion, it's unnecessary to define the function in render()
.
I have made a little revisions to the original example above to show that.
From example you provided, the usage of divider may be like:
const divider = (divider, key) => {
const classes = classNames( 'divider', divider.class);
return (<li key={key} className={ classes }></li>);
};
return (<ul>{this.state.dividerList?
this.state.dividerList.forEach(divider) : null}</ul>);
I think the reason of this is just for maintainability, someone may want all DOM creating code inside the render()
for easy tracing when DOM structure returned is really complicated (and arrow function is lightweight), but as I said it's subjective, it really could be defined outside.
In this kind of case, I used to do below instead, and it seems what you provided is more elegant, but if you defined that function outside of render()
, things become distractive to me.
let dividers = [];
if (this.state.dividerList) {
this.state.dividerList.forEach((divider, key) => {
let classes = classNames( 'divider', divider.class);
dividers.push((<li key={key} className={ classes }></li>));
});
}
return (<ul>{dividers}</ul>);
So another function you provided which aims at DOM manipulations feature is totally proper and well to be defined outside.