-
Notifications
You must be signed in to change notification settings - Fork 7
Best Practices For Wrtiting A Component
- Each component should be in a separate file.
- The filename should be in
PascalCase
e.gclass FooBar extends React.Component {}
. - Each component should have corresponding tests.
- When writing a stateful component you should order your component as follows:
class Foo extends React.Component {
constructor(props) {
super(props);
};
componentWillMount() {
...
}
componentDidMount() {
....
}
classMethod1() {
....
}
classMethod2() {
....
}
handler1 = () => {};
handler2 = () => {};
render: void;
}
First, your constructor should be the first thing you declare after your class
please do note that this applies when you don't have class property
otherwise they should come first.
constructor
The second thing that should follow is React lifecycle methods, yes I know the constructor
is part of the lifecycle methods too but since it's the method that start's the birth of your component I think it should stay there.
componentWillMount
componentDidMount
componentWillUpdate
then any class methods
you might want to include in your class that don't act as handlers for the component, e.g
isValidUser() {
....
}
and then finally, your handlers clickHandlers
or eventHandlers
onClickSubmit()
onChangeDescription()
the last thing should be the render method
render() {}
- When conditionally rendering element(s) or component(s) inline, JavaScript logical
&&
operator should be used. For example,
Don't do this(notice the ''):
render() {
const { showModal } = this.state.showModal;
return (
<div>
{
showModal
? (<Modal />)
: ''
}
</div>
);
}
Also, don't do this(notice the null):
render() {
const { showModal } = this.state.showModal;
return (
<div>
{
showModal
? (<Modal />)
: null
}
</div>
);
}
Do this:
render() {
const { showModal } = this.state.showModal;
return (
<div>
{
showModal
&& (<Modal />)
}
</div>
);
}
- action types - use constants,
[NOUN]_[VERB]
, eg.SEARCH_TAGS_SUCCESS
orLOAD_CONTRIBUTIONS_SUCCESS
- action creators - [verb]_noun eg. loadTagsSuccess(), loadContributionsSuccess()
- You don't need to keep typing function
- It lexically captures the meaning of this
with arrow functions, you can write concise code
export const loadContributionsSuccess = (contributions) => {
return {
contributions,
type: LOAD_CONTRIBUTIONS_SUCCESS
};
};
you can make this action creator even more concise. if the only statement an arrow function contains is the return statement you can wrap the curly brace that indicates the starting block and the end with parenthesis so that parser or the engine understands this as an expression rather than a block this makes your code more compact.
export const loadContributionsSuccess = contributions => ({
contributions,
type: LOAD_CONTRIBUTIONS_SUCCESS
});