React is a popular library for creating web apps and mobile apps.
In this article, we’ll look at some tips for writing better React apps.
Fix the ‘Warning: setState(…): Cannot update during an existing state transition’ Error
To fix this error, we shouldn’t call methods in the render
method.
For instance, in the constructor, we put our state change methods:
this.handleButtonTrue = this.handleButtonChange.bind(this, true);
this.handleButtonFalse = this.handleButtonChange.bind(this, false);
Then in our render
method. we write:
<Button onClick={this.handleButtonTrue}>true</Button>
<Button onClick={this.handleButtonFalse}>false/Button>
When to use React setState Callback
We should use the React setState
‘s callback when we need to run some code that always runs after a state change.
For instance, we can write:
changeTitle(event) {
this.setState({ title: event.target.value }, () => {
this.validateTitle();
});
},
validateTitle() {
if (this.state.title.length === 0) {
this.setState({ error: 'no blank title' });
}
},
We call setState
to change the title
state.
Then we run validateTitle
to validate the latest value of the title
state.
React Prop Validation for Date Objects
We can validate that date objects are passed in as props with the instanceof
method.
We can write:
PropTypes.instanceOf(Date)
to do the validation.
Best Way to Access Redux Store Outside a React Component
We can access a Redux store outside a React component by exporting the value returned from createStore
.
Then we can use that value anywhere we like.
For instance, in store.js
, we write:
const store = createStore(myReducer);
export store;
Then in app.js
, we write:
import { store } from './store'
store.dispatch(
//...
)
If we want to use multiple stores, we can write a function that creates a store if it doesn’t exist and return a promise with the store.
Then we can use that to get the store.
Wrapping One Component into Another
To let us wrap one component in another, we create a wrapper component with that takes the children
prop
For instance, we can write:
const Wrapper = ({children}) => (
<div>
<div>header</div>
<div>{children}</div>
<div>footer</div>
</div>
);
const App = ({name}) => <div>Hello {name}</div>;
const App = ({name}) => (
<Wrapper>
<App name={name}/>
</Wrapper>
);
We create a Wrapper
component which takes the children
prop.
Then we create a App
component which we put inside our Wrapper
component.
We can also use render props to pass components into another.
This means we pass the whole render
function into another component.
For instance, we can write:
class Wrapper extends React.Component {
state = {
count: 0
};
increment = () => {
const { count } = this.state;
return this.setState({ count: count + 1 });
};
render() {
const { count } = this.state;
return (
<div>
{this.props.render({
increment: this.increment,
count: count
})}
</div>
);
}
}
class App extends React.Component {
render() {
return (
<Wrapper
render={({ increment, count }) => (
<div>
<div>
<p>{count}</p>
<button onClick={() => increment()}>Increment</button>
</div>
</div>
)}
/>
);
}
}
We created a Wrapper
which takes a render
prop that takes a function that renders components.
We passed in a value for the render
prop in App
.
Then that’s called within Wrapper
with the object that as the increment
and count
properties.
The increment
method is passed in from App
and as well as the count
state.
Validate the PropTypes of a Nested Object in React
We can validate prop types of a nested object bu using the shape
method.
For instance, we can write:
import PropTypes from 'prop-types';
propTypes: {
data: PropTypes.shape({
firstName: PropTypes.string.isRequired,
lastName: PropTypes.string
})
}
We call the PropTypes.shape
method with an object that describes the structure of the data
prop.
We have 2 strings and isRequired
indicates that it’s required.
How to Add Comments in React?
We can add comments by putting them between curly braces.
For instance, we can write:
<div>
{/* button click */}
<Button whenClicked={this.handleClick}>click me </Button>
<List />
</div>
Out comment is within the curly braces.
They’re the same as regular JavaScript comments.
Conclusion
We can add comments if we put them between the curly braces.
We shouldn’t call setState
in our render
method.
A Redux store can be accessed outside a React component.
We can nest child components by creating a wrapper component that takes the children
prop.
Or we can accept a render
prop in our component that renders components.