It won’t be far-fetched to say that ReactJS is the most loved JavaScript library. In a 2020 StackOverflow survey, over 68% of developers said that they enjoyed their experience working with react.
ReactJS comes with unique features like reusable components and dedicated debugging tools, making it a popular choice for many JavaScript users. Tech giants like Facebook, Netflix, and Amazon are known users of React.
As a developer, it is crucial to focus on writing clean code based on the widely accepted coding standard and proper folder structure. In this article, we will learn some of these best practices in ReactJS that will help build your confidence in writing a better code.
1. Project Structure
Project structure is concerned with making a maintainable code. You have to take care of the following things to have a nicely structured project.
Folder Layout
To create a project, run:
npx create-react-app my-app
cd my-app
npm start
But, you’ll need to have Node >=14.0.0 and npm >=5.6 on your machine.
After this, a new base react application structure is generated which can be further nested based on requirements as shown below:
src
|
|- assets/
| |- styles
| |- images
|
|- components/
| |- card
| | |- Index.js
| |- buttons
| |- forms
|
|- layout
| |- header
| |- footer
| |- container
| |- sidebar
|
|- pages
| |- Dashboard
| | |- MainPage.js
| | |- BarGraph.js
|
|- store
| |- actions
| | |- action.js
| |- reducers
| | |- reducer.js
| |- index.js
|
|- routes
| |- route.js
| |- index.js
|
|- utils
| |- constants
| | |- constant.js
| |- helper
| | |- helperFile.js
|
|- config
| |- config.js
|
|- locale
| |- en.json
|
|- env
| |- .env
The 7-1 Pattern
Let’s get back to architecture, shall we? I usually go with what I call the 7-1 pattern: 7 folders, 1 file. You have all your partials stuffed into 7 different folders and a single file at the root level (usually named main.scss) which imports them all to be compiled into a CSS stylesheet.
Ideally, we can come up with something like this:
sass/
|
|- abstracts/
| |- _variables.scss # Sass Variables
| |- _functions.scss # Sass Functions
| |- _mixins.scss # Sass Mixins
| |- _placeholders.scss # Sass Placeholders
|
|- base/
| |- _reset.scss # Reset/normalize
| |- _typography.scss # Typography rules
| ... # Etc.
|
|- components/
| |- _buttons.scss # Buttons
| |- _carousel.scss # Carousel
| |- _cover.scss # Cover
| |- _dropdown.scss # Dropdown
| ... # Etc.
|
|- layout/
| |- _navigation.scss # Navigation
| |- _grid.scss # Grid system
| |- _header.scss # Header
| |- _footer.scss # Footer
| |- _sidebar.scss # Sidebar
| |- _forms.scss # Forms
| ... # Etc.
|
|- pages/
| |- _home.scss # Home specific styles
| |- _contact.scss # Contact specific styles
| ... # Etc.
|
|- themes/
| |- _theme.scss # Default theme
| |- _admin.scss # Admin theme
| ... # Etc.
|
|- vendors/
| |- _bootstrap.scss # Bootstrap
| |- _jquery-ui.scss # jQuery UI
| ... # Etc.
|
`- main.scss # Main Sass file
For the compilation part, we use node-sass.
Run the following command on your terminal:
npm install node-sass
You might also like: Getting started with React Native: Core Architecture of React Native
2. Coding Standard
Everything will be shown with code, so buckle up!
Import in Order
Import things in a particular order to improve code readability.
// Bad
import React from 'react';
import ErrorImg from '../../assets/images/error.png';
import styled from 'styled-components/native';
import colors from '../../styles/colors';
import { PropTypes } from 'prop-types';
// Good
import React from 'react'; // built-in
import { PropTypes } from 'prop-types'; // external
import styled from 'styled-components/native'; // external
import ErrorImg from '../../assets/images/error.png'; //internal
import colors from '../../styles/colors'; //internal
Component Naming
Use PascalCase and camelCase for components and instances respectively.
// Bad
import bookingCard from './BookingCard';
const BookingItem = <BookingCard />;
// Good
import BookingCard from './BookingCard';
const bookingItem = <BookingCard />;
Quotes
Use double quotes for JSX attributes and single quotes for all other js
JSX in parenthesis
If your component spans more than one line, always wrap it in parentheses.
// Bad
return <Component variant="primary">
<Child />
</Component>;
// Good
return (
<Component variant="primary">
<Child />
</Component>
);
Self-closing tags
Use of self-closing tags for components that do not have children really improves code readability.
// Bad
<Component variant="any"></Component>
// Good
<Component variant="any" />
Use Implicit return
Use the JavaScript feature of implicit return to write beautiful code.
// Bad
const addition = (a, b) => {
return a + b;
}
// Good
const addition = (a, b) => a + b;
Use Fragment
Always use fragment over div because one less node is created in virtual DOM.
// Bad
return (
<div>
<ComponentA />
<ComponentB />
<ComponentC />
</div>
)
// Good
return (
<>
<ComponentA />
<ComponentB />
<ComponentC />
</>
)
Use Ternary Operators
// Bad
const { role } = user;
if(role === ADMIN) {
return <AdminUser />
}else{
return <NormalUser />
}
// Good
const { role } = user;
return role === ADMIN ? <AdminUser /> : <NormalUser />
Use Advantage of ES6 features
// Bad
const {role} = user
switch(role){
case ADMIN:
return <AdminUser />
case EMPLOYEE:
return <EmployeeUser />
case USER:
return <NormalUser />
}
// Good
const {role} = user
const components = {
ADMIN: AdminUser,
EMPLOYEE: EmployeeUser,
USER: NormalUser
};
const Component = components[role];
return <Component />;
// Bad
return (
<>
<div> {user.name} </div>
<div> {user.age} </div>
<div> {user.profession} </div>
</>
)
// Good
const { name, age, profession } = user;
return (
<>
<div> {name} </div>
<div> {age} </div>
<div> {profession} </div>
</>
)
// Bad
const userDetails = user.name + "'s profession is" + user.profession
return (
<div> {userDetails} </div>
)
// Good
const userDetails = `${user.name}'s profession is ${user.profession}`
return (
<div> {userDetails} </div>
)
Similarly, other smart ways to standardize your ReactJS code are:
- Use higher-order functions(map, filter, forEach, reduce, etc.)
- Use ES-lint or prettier for formatting
- Write test for each component. Commonly used ReactJS testing frameworks are jest or enzyme.
- Decompose larger components into smaller ones, and function-specific Function-specific components can be standalone, which makes testing and maintenance easier.
- Use propTypes for Type Checking and Preventing Errors or use typescript.
You might also like: Switching to React Native from Ruby on Rails
3. Security
Security using JSON Web Token (JWT):
- Please avoid keeping JWT tokens based on Local Storage. As it would be very easy for someone to get a token using the browser’s Dev tools console and write.
console.log(localStorage.getItem('token'))
- Store your tokens to an HTTP cookie rather than localStorage or you can keep your tokens to your React app’s state.
- Always make sure you use HTTPS in place of HTTP. This will give assurance for your web-based app to provide a valid certificate that can be sent over a secure SSL network.
4. Conclusion
A proper code in ReactJS is always the one that focuses on readability, security, and reusability. However, with a challenging project in mind, one might not always be careful about these basic practices.
With this blog, I have tried to give you a deeper insight into how ReactJS works, how to add security to your code, and how to build components and applications. I hope this list of best practices for React Developers helps you put your project on the right track and avoid any potential problems later down the road.
ReactJS is a widely used JavaScript library for building interactive user interfaces. Read about our collaboration with Almond to build a mobile commerce app based on React that enables communities in developing countries to grow revenue.
Don’t let subpar React development hold back your next big project. Our dedicated teams follow the best practices that ensure success. Drop us a message or simply book a free consulting call to learn more about how our development team can quickly gear up your project!