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.
Form Input Validation with React
We can do form validation with our own checks.
For instance, we can do the value checks within the submit handler.
We can write:
class Signup extends React.Component{
constructor(props){
super(props);
this.state = {
isDisabled:true
}
this.submitForm = this.submitForm.bind(this);
}
handleChange(e){
const target = e.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
if (e.target.name==='firstname'){
if (e.target.value === '' || e.target.value === null){
this.setState({
firstnameError: true
})
} else {
this.setState({
firstnameError: false,
firstName: e.target.value
})
}
}
if (e.target.name==='lastname'){
if(e.target.value==='' || e.target.value === null) {
this.setState({
lastnameError: true
})
} else {
this.setState({
lastnameError:false,
lastName:e.target.value
})
}
}
}
submitForm(e){
e.preventDefault();
const data = {
firstName: this.state.firstName,
lastName: this.state.lastName
}
}
render(){
return (
<form>
<div>
<input type="text" id="firstname" name="firstname" placeholder="firstname" onChange={(e)=>{this.handleChange(e)}} />
<label htmlFor="firstname">firstname</label>
{this.state.firstnameError ? 'Please Enter some value' : ''}
</label>
<div>
<input type="text" name="lastname" placeholder="lastname" onChange={(e)=>{this.handleChange(e)}} />
<label htmlFor="lastname">lastname</label>
{this.state.lastnameError ? '>Please Enter some value' : ''}
</label>
</div>
<button onClick={this.submitForm}>Signup</button>
</form>
);
}
}
We have the first name and last name fields.
We watch for their inputted values and check for them in the handleChange
method.
target.name
has the value of the name attribute.
target.value
has the inputted value.
And then in each field, we check if it’s filled in.
In the submitForm
method, we get the data and then submit it.
We’ve to call preventDefault
to stop the default submit behavior.
To make our lives easier, we can use a package like React Hook Forms to do form validation.
For instacne, we can write:
import React from "react";
import useForm from 'react-hook-form';
function Form() {
const { useForm, register } = useForm();
const contactSubmit = data => {
console.log(data);
};
return (
<form onSubmit={contactSubmit}>
<div className="col-md-6">
<fieldset>
<input name="name" type="text" size="30" placeholder="Name" ref={register} />
<br />
<input name="email" type="text" size="30" placeholder="Email" ref={register} />
</fieldset>
<fieldset>
<button id="submit" value="Submit">
Submit
</button>
</fieldset>
</div>
</form>
);
}
We use the useForm
hook that comes with the package.
And then we call register
returned from useForm
to get register the input fields so that we get the form values with the submit handler.
The values are in the data
parameter of the contactSubmit
function.
Importing CSS files in Isomorphic React Components
In isomorphic React components, we can check for the environment before we import our CSS.
For instance, we can write:
if (process.env.BROWSER) {
require("./style.css");
}
We check the environment variables before we import the CSS.
We import only in the browser environment.
We can then define a Webpack plugin to set the environment variable:
plugins: [
// ...
new webpack.DefinePlugin({
"process.env": {
BROWSER: JSON.stringify(true)
}
})
]
How to Render Child Components in React Recursively
We can render child components recursively by rendering the same component within the component.
For instance, we can write:
import React, { Component, PropTypes } from 'react'
export default class Comments extends Component {
render() {
const { comments } = this.props;
return (
<div>
{comments.map(comment =>
<div key={comment.id}>
<span>{comment.content}</span>
{comment.comments && <Comments comment={comment.comments} />}
</div>
)}
</div>
)
}
}
Comments.propTypes = {
comments: PropTypes.array.isRequired
}
We create a Comment
component that takes a comments
prop that’s rendered into an array of Comment
components.
We make the comments
prop required and an array so that we can render them if they’re passed in.
React-Router is Refreshing the Page when Using a Tag
To stop refreshing the page when we click an a
tag, we should use the Link
component.
For instance, we can write:
import React from "react";
import { Link } from 'react-router-dom';
export class App extends React.Component {
render() {
return (
<Link to="/foo">Click Here</Link>
)
}
};
We use the Link
tag with the to
prop that has the route.
Conclusion
We can validate form inputs in many ways.
To make our lives easier, we should use a form validation library
Also, we check the environment before we import CSS in an isomorphic React component.
We use the Link
component for links if we use React Router.