React is a well known open-source JavaScript library that is used to create unique and innovative applications. It was created by Facebook and allows integration with many exciting components, libraries and frameworks. Also, developers can make their own components. Developing an app with React is not as simple as it looks. Knowing the react best practices will help you to develop an effective app within less time. Still, if you are not aware of the react best practices, then this blog is for you. Let us see the React best practices.
Know the reasons to use React for app development at- Why you should build your app with react native?
1.1 Folder layout-
Architecture mainly focuses on reusable components of react developer architecture so as to share the design pattern among multiple internal projects. So the component-centric file structure should be used that means all the files related to a different component (Javascript, assets, CSS etc.) should be kept under a single folder.
Components | --Login | --tests-- --Login.test.js --Login.jsx --Login.scss --LoginAPI.js
This one is another approach used in grouping the file types. In this, the same type of files is kept under one folder. Here, same type of files is kept under one folder. For instance,
APIs | --LoginAPI --ProfileAPI --UserAPI Components | --Login.jsx --Login.test.js --Profile.jsx --Profile.test.js --User.jsx
Above structure is the basic example. The folders can be further nested based on requirements.
1.2 Css in JS-
In huge projects, theming and styling can be challenging tasks like maintaining nig scss files. Hence, the concept of CSS-in-JS solutions comes into focus. Following libraries are based on it-
Among those libraries, you can use as per your requirement such as, for complicated themes, you can select styled-components or Glamorous.
2.1 Naming Conventions-
When you work with React, generally you are using JSX(Javascript extensions) files. A component that you create for React should be named in Pascal case, or upper camel case. This translates to names without spaces and capitalizing the first letter of every word. If you have to create a function that submits a form, you should name it SubmitForm in upper camel case, instead of SubmitForm, submit_form. Generally, Upper camel case is called the Pascal case.
For globally used Constant fields in the application, try to use only capital letters. For example, PI = “3.14”;
2.2 Avoid unnecessary DIV-
When there is a single component to be returned, no need to use <div>.
return ( <div> <Button>Close</Button> </div> );
Whenever there are multiple components to be returned, use in shorthand form <> as below-
return ( <Button>Close</Button> );
2.3 Consolidate duplicate code – DRY your code-
For all code, common rule is to keep it as brief and concise as possible. One way to do this is to avoid duplication- Don’t Repeat Yourself(DRY). One can do this by scrutinizing the code for patterns and similarities. If you find any, it is possible you’re repeating code and there’s scope to remove duplication. Mostly, rewriting can make it more concise. It highly depends on the reusability principle in React.
For instance, you have to add multiple buttons that includes icons, rather than adding markup for each button, you just need to use IconButton component. You could go further by mapping everything into an array.
const buttons = ['facebook', 'twitter', 'youtube']; return ( <div> { buttons.map( (button) => { return ( <IconButton onClick={doStuff( button )} iconClass={button} /> ); } ) } </div> );
2.4 Apply ES6 Spread Function-
It will be an easy and productive way to use ES6 functions to pass an object property. By using {…props} between open and close tag will automatically add all props of object.
let propertiesList = { className: "my-favorite-props ", id: "myFav", content: "Hello my favourite!" }; let SmallDiv = props => <div {... props} />; let mainDiv = < SmallDiv props={propertiesList} />;
You can make use of spread function:
For the repetitive use of functions, don’t use spread function when,
2.5 Write Tests for each component-
It is better to write test cases for each component developed because it reduces the chances of errors when code is deployed. You can check all possible scenarios in unit testing. Jest or enzymes are mostly used react test frameworks.
2.6 Code should execute as expected and be testable-
Code that you write should behave as expected and be quickly and easily testable. It is good to name your test files identical to source files with .test suffix. Then it’ll be easy to find test files. You can use JEST to test react code.
3.1 Divide into small components-
Divide large components into small components like each component performs one function as much as possible. It becomes easy to manage, test and reuse small components.
3.2 Appropriate Naming and Destructuring Props-
To keep clean and readable code, use meaningful and short names for component props. Use props destructing feature of function that discards the need to write props with each property name and can be used as it is.
const funcDestruct = ({name, title}) => { return ( <div> <p>{name} – {title}</p> </div> ) }
With props destructing, you can directly use name and title without using props.name or props.title.
3.3 Use Functional or Class Components based on Requirement-
If you’ve to show User Interfaces without implementing any logic or state change, use functional components in place of class components as functional components are efficient here. For instance-
// class component class Cat extends React.Component { render () { let { badOrGood, type, color } = this.props; return <div classname="{type}">My {color} cat is { badOrGood } </div>; } } Vs. //function component let Cat = (badOrGood, type, color) => <div classname="{type}">My {color} cat is { badOrGood }</div>;
3.4 Use propTypes for Type Checking and preventing errors-
It is better to do type checking for props passes to a component that can help to prevent bugs. Let us see how to use-
React.PropTypes:
import React, { Component } from “react”; import PropTypes from “prop-types”; class PropTypeExample extends Component { render() { const { username } = this.props; return <h1>Welcome, { username }</h1> } } PropTypeExample.PropTypes = { name: PropTypes.string.isRequired };
4.1. HTTP Authentication-
Authentication should be secure as the client-side authentication and authorization can be exposed to many security defects that may destroy the protocols in application. Most commonly used technique for adding authenticity can be validated using AuthO, React Router, OAuth, JSON Web Token(JWT), PassportJs
Security with JWT-
4.2. Broken access control-
In appropriate management of restrictions and limitations on authenticated users can use misuse of unauthorized data and functionality of React native app. In some cases unauthorized users can also change the primary key of data and control the functionality of the application. To ensure security from unauthorized access, follow these practices:
4.3 Secure Against DDoS Attacks-
Security issues that occur when the app has loopholes and it masks the IPs. This will confine the communication caused because of the termination of services. Here are some methods to stop this:
4.4 SQL Injection-
It is related to data manipulation. Because of this, attackers can modify data with or without user’s permission or can get any confidential information by executing arbitrary SQL code.
Solution to this is-
To avoid the SQL injection attacks, first validate API call functions against respective API schemas. So as to handle the issue of time-based SQL injection attacks, you can use timely validation of schema to avoid any suspicious code injections. Other effective way to secure against SQL vulnerability is using SSL Certificate.
4.5 Cross-Site Scripting (XSS)-
Here you came to know, how to add security to react software. The React best practices will offer you some typing options and more explicit codes. The above react best practices will help you to eliminate any future development complication and also keep you project on the right track. We at solace infotech follows react best practices and develop secured react software. If you are thinking to develop a software with React, consult with Solace experts. We are here to help you through consultation and development. You can hire react developers of Solace team for an effective and secured react development. We will be happy to help you.