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.
React Button Redirect Page on Click
We can redirect to a page when we click on an element by getting the history
object.
For instance, we can write:
import React from 'react';
import { useHistory } from "react-router-dom";
function LoginPage () {
const history = useHistory();
const onClick = () => {
history.push('new-page');
}
return (
<div>
<button
onClick={onClick}
>
Login
</button>
</div>
);
}
export default LoginPage;
We get the native history
object with useHistory
Then we define the onClick
function to call history.push
to navigate to a new page.
If we’re using class components, we can write:
import { withRouter } from 'react-router-dom';
class LoginPage extends Component {
constuctor() {
this.routeChange = this.routeChange.bind(this);
}
onClick() {
this.props.history.push('forgot-password');
}
render() {
return (
<div>
<button onClick={onClick}>Forgot password?</button>
</div>
);
}
}
export default withRouter(LoginPage);
We have the LoginPage
class component.
To make the history
prop available to the component, we pass it to withRouter
.
We have the onClick
method that calls the this.props.history.push
method to navigate to the new page.
The routerChange
method has to be bound to the component with bind
so that we set the component class as the value of this
.
Render Boolean Value in JSX
We can render boolean value in JSX by converting it to a string first.
For instance, we can write:
Boolean Value: {bool.toString()}
or:
Boolean Value: {String(bool)}
or:
Boolean Value: {'' + bool}
or:
{`Boolean Value: ${bool}`}
or:
Boolean Value: {JSON.stringify(bool)}
There are many ways to convert a boolean value into a string.
They’re all good except for the concatenation, which may be confusing.
Using event.target with React Components
We can use event.target
to get a DOM element’s properties.
We can use the dataset
property to get attributes prefixed with the data-
prefix.
They’re considered custom attributes that let us pass data around with an element.
For instance, if we have a button, then we can write:
<button
data-foo="home"
data-bar="home"
onClick={this.props.onClick}
/>
Button
</button>
Then we can write:
onClick(e) {
console.log(e.target.dataset.bar, e.target.dataset.foo);
}
to get the foo
and bar
properties from the button that we clicked with the dataset
property.
dataset.foo
has the value of the data-foo
attribute.
dataset.bar
has the value of the data-bar
attribute.
Adding a .env File to React Project
If we have a create-react-app project, we can add an .env
file to add the environment variables.
Inside the file, any keys that are prefixed with the REACT_APP_
prefix are read into the app.
So in our .env
file, we can write:
REACT_APP_API_KEY=secret
We can then use the environment variable values by writing:
fetchData() {
fetch(`https://example.com?api-key=${process.env.REACT_APP_API_KEY}`)
.then((res) => res.json())
.then((data) => console.log(data))
}
We read the environment variable value with the process.env
object.
How to Pass Multiple Parameters to Input’s onChange Handler
We can pass in multiple parameters to an input’s onChange
handler.
To do that, we can write:
<Input
type="text"
value={this.state.name}
onChange={this.onChange.bind(this, this.state.user.id)}
/>
Then we can define our onChange
method by writing:
onChange(`userId`, event) {
const newName = event.target.value;
},
We have whatever we pass in as the first argument.
And the last argument is the object.
How to Catch and Handle Error Response 422 with Redux and Axios
We can call dispatch
to dispatch the action within a React component.
For instance, we can write:
axios({
method: 'post',
responseType: 'json',
url: `${SERVER_URL}/login`,
data: {
username,
password
}
})
.then(response => {
dispatch(setUser(response));
})
.catch(error => {
dispatch({ type: AUTH_FAILED });
dispatch({ type: ERROR, payload: error.data.error.message });
});
We make a POST request with Axios.
Then in the then
callback, we get the response
and call dispatch
and our setUser
action creator.
And then we call the catch
method with a callback to handle errors.
We call dispatch
with or without a payload.
Calling dispatch
would update the store with the new state value.
Conclusion
We can redirect pages on click.
And we can handle errors with Redux by calling dispatch
to update the stores.
Booleans can be rendered if we convert them to a string.