A Development Environment for React.js – Setting up and Optimizing it

React and its associated libraries are growing at an astonishing pace. It’s not only being used to build complex user interfaces but also being implemented in online stores, e-commerce websites and other businesses to build fast and scalable apps. 

If you are just getting started with React.js, the first challenge is to get your development environment set up and ready for coding. This can be a little tricky as there are so many different tools, libraries, and frameworks that you need to work with together. In this article we will walk you through the process of setting up an optimal React development environment on macOS or Windows.

In this post, we will look at what React is, why it became so popular recently, how to set up a development environment for React and optimize it for your project.

1. Get the tools you need

To get started, you will need to install a few different tools. 

  • A text editor for writing code, like VS Code or Sublime Text.
  • A browser for testing and debugging your application, like Chrome or Safari.
  • A code compiler that can translate your code from JavaScript into another language. 
  • A build tool that can generate the final code for your application. 
  • A package manager for installing the different tools you need for your application.

This depends on a number of things – your project type, the OS you are working with, the software versions of the tools you are using, etc.

2. Install Node.js and create an npm script

Next, you will need to install Node.js. Visit the official link and download to install. The next step is to set up a React Boilerplate. Setting up the React environment depends on the Node version. 

For old versions of Node and Boilerplate (before 8.10 and 5.6 respectively)

Install Boilerplate globally. To do so, run the following command in the terminal or cmd prompt.

npm install -g create-react-app

If successful, the terminal should show the following output.

For versions of Node and Boilerplate (8.10 and 5.6 and after respectively), the machine uses the latest features of Javascript. Run the command given below.

npx create-react-app my-app

The output should be as given below, thus creating the app name my-app. This can be changed according to your preference. However, this will also be used and be displayed in all future steps.

Running the project requires the following commands as shown in the output above.

cd my-app

npm start

The output will be as shown in the terminal snapshot below.

The App should now be viewable in the browser, as shown.

3. Set up a React development environment with Create-React-App

  • Create-React-app is a tool that can set up a new React development environment for you, including all the necessary Node modules, development server, and build configuration. 
  • Once you have installed create-react-app and run the create-react-app command, it will ask you a couple of questions, after which it will create a new React development environment. 
  • The create-react-app command is also a npm script.

The command is: 

create-react-app myapp

The above command should create a directory my-app in your current directory with all the necessary files required to run a React App. A snapshot of the directory so created is as given below.

The significant files here are index.html and index.js. The index.html file has a div element (id=”root”), which houses all the steps rendered and the React code will be stored in the index.js file.

4. Starting the Development Server:

To do that, go into the current directory (myapp in this case) and execute the following command line.

npm start

The following message should come up on your compiler.

You can go to the URL shown above to see the changes you are making in your App getting reflected. By default, the above URL will show the below page:

5. Optimizing your Development Environment

Debugging 

When you’re working in a development environment, you can easily debug your application using Chrome. 

  • You can debug your application using the built-in debugger in Chrome, which allows you to set breakpoints, view variable values, and step through your code.
  • To use the debugger, you need to enable the developer tools in Chrome. 
  • You can also use the debugger with a remote debugger, which allows you to run the debugger on a separate computer, like your laptop.

Optimizing Your Environment for React Development

While your development environment is ready, you can also optimize it for React development by taking a few extra steps. 

  • The first thing you need to do is install the React development tools. The React development tools provide several features, including automatic refreshing of your application while you are making changes and live reloading your application when you make a change. 
  • Another thing you need to do is install the ESLint code linter for React – The ESLint code linter can find common mistakes and errors in your code, like missing semicolons or using incorrect syntax. 
  • The ESLint code linter also provides suggestions for improving your code, like using a better naming convention or applying a best practice.

Conclusion

React gives you the ability to create reusable UI components that can be used across different parts of your application. With React, you can build your application using these reusable components, which are faster to create, easier to maintain, and easier to understand. Setting up your development environment is the first step towards creating applications with React. When you are done setting up your environment, you can continue with learning how to build your application with React.

 

 

React optimization tips for improved performance

Optimizing application performance is a critical requirement for developers. Delivering a positive user experience is essential and determines the app’s success. In research, Akamai, the world’s leading CDN service with clients like The Washington Post, Flipkart, and Netflix, found that a one-second delay in application load time can result in a 7% reduction in conversions.

If your application is built on ReactJS, fortunately, there are several optimization techniques you can implement to accelerate the performance. In this guide, we elaborate on tips for using React optimization to keep performance high as your app scales.

1. Keep component state local where necessary

In ReactJS, a state update in the parent component re-renders the parent and all its child components. This is why you must ensure that the re-rendering of the components happens only when necessary.

The easiest way to achieve this is to separate the code that handles component states and make it local.

Here’s the example code:

import { useState } from “react”;

export default function App() {

  return (

   <div>

    <FormInput />

    <ChildComponent />

   </div>

  );

}

function FormInput() {

  const [input, setInput] = useState(“”);

  return (

   <div>

    <input    

type=”text”    

value={input}

onChange={(e) => setInput(e.target.value)} 

/>

    <h3>Input text: {input}</h3>

   </div>

  );

}

function ChildComponent() {

console.log(“child component is rendering”);

return <div>This is child component.</div>;

}

Only the input field is responsible for the component state in this code. We separate the input and the state into a FormInput component, making it a sibling to the ChildComponent. Now when the FormInput component state changes, only the component re-renders.

While there will be some instances where you cannot avoid the global component state, this method can still significantly optimize ReactJS performance.

2. Memoizing React components

Memoization is a React optimization technique that caches a component-rendered operation to save the result at the moment. Then for the same input at other instances, it serves the results from the cache memory. It’s the same as for any different caching technique, but with React, it works better as it is integrated at the code level.

Let’s understand this React optimization technique with this code:

import { useState } from “react”;

export default function App() {

  const [input, setInput] = useState(“”);

  const [count, setCount] = useState(0);

  return (

   <div>

    <input    

type=”text”

     value={input}

     onChange={(e) => setInput(e.target.value)}

    />

    <button onClick={() => setCount(count + 1)}>Increment counter</button>

    <h3>Input text: {input}</h3>

    <h3>Count: {count}</h3>

    <hr />   

<ChildComponent count={count} />

   </div>

  );

}

function ChildComponent({ count }) {

console.log(“child component is rendering”);

  return (

   <div>

    <h2>This is a child component.</h2>

    <h4>Count: {count}</h4>

   </div>

  );

}

Here the input field update re-renders both the App component and ChildComponent. But we only want the ChildComponent to re-render because it is responsible for updating the UI. So, we memoize the ChildComponent to optimize the app’s performance.

3. Using React.memo()

React.memo is one of the higher-order components you can use in your ReactJS app to wrap a purely functional component to prevent its re-rendering if the props received in that component never change.

Here’s a syntax example to achieve this:

import React, { useState } from “react”;

// …

const ChildComponent = React.memo(function ChildComponent({ count }) {

console.log(“child component is rendering”);

  return (

   <div>

    <h2>This is a child component.</h2>

    <h4>Count: {count}</h4>

   </div>

  );

});

If the count prop never changes here, React will skip rendering the ChildComponent to reuse the previously rendered result. This can significantly improve React performance.

React.memo() is a good React optimization technique to be used with primitive values, such as a number in our example. Primitive values are always referentially equal and return true if their value never changes. While non-primitive values like objects, including arrays and functions, always return false because they point to different spaces in memory between re-renders.

Here is an example code passing a function to the child component: 

import React, { useState } from “react”;

export default function App() {

  // …

  const incrementCount = () => setCount(count + 1);

  return (

   <div>

    {/* … */}   

<ChildComponent count={count} onClick={incrementCount} />

   </div>

  );

}

const ChildComponent = React.memo(function ChildComponent({ count, onClick }) {

  console.log(“child component is rendering”);

  return (

   <div>

    {/* … */}

    <button onClick={onClick}>Increment</button>

    {/* … */}

   </div>

  );

});

In this code, the incrementCount function passed to the ChildComponent makes the component re-render when the function is redefined. To prevent regular redefining of the function, we can use a useCallback Hook that returns a memoized version of the callback between renders.

This will save memory and make the ReactJS app perform faster and more efficiently, avoiding unnecessary re-renders.

Conclusion

ReactJS is one of the most widely-used frontend development languages. It requires less code for building apps and can be scaled easily. And to keep the performance high when you are building scalable apps, we are sure these tips will help optimize the performance of your React application easily.

Talent500 is the platform for ReactJS developers to explore career-redefining opportunities with Fortune 500 companies and fast-growing startups. Sign up here to join our elite talent pool.

 

Using React with Rails: Things to consider

Frontend development has come a long way in the last decade. The domain is rapidly developing with new technologies to utilize modern infrastructure more efficiently. Of all the technologies, React remains a significant player. According to Statista, ReactJS is the second most widely used JavaScript library, with a market share of 42.62%.

Developers are using ReactJS to make their Ruby on Rails applications more powerful. This article will look at things you need to consider while using React with Rails.

When to use React and Rails?

Ruby on Rails and React are both standalone frameworks. You can build applications using either Rails or ReactJS, but there are scenarios where combining the two offers a technological edge. If you are not sure when to use React with Rails, here are some preferred applications:

  • Complex simple-page applications
  • Applications with a large volume of dynamic content
  • Mobile-first applications that need to be scaled rapidly
  • Applications handling larger database
  • Applications with higher performance speed

If you are working on any such application, then you can plan to use the two technologies in combination.

Now let’s look at the considerations to make.

1. Is fast development possible?

Ruby on Rails has many built-in modules and code libraries that developers can use to rapidly build enterprise applications. There are also options to strengthen communication with frontend libraries like ReactJS. However, to reduce cost and development time, you need to ensure that developers in your team understand how to build a Ruby on Rails app with a ReactJS frontend. Some prerequisites exist to fully utilize the combination for product development, like understanding protocols to transfer data between Rails backend and React frontend.

Also, there are tricks to clean up your React components that can make your apps much faster. It helps you scale the performance of the applications without increasing the resources.

2. What is your app speed requirements? 

Not every app benefits from using React and Ruby on Rails as the tech stack. If your app has to handle a high volume of dynamic data or too much traffic, you can build your app using any one of the frameworks.

However, it’s the best tech stack if your app needs to load lightning fast, even with dynamic content, and handle increasing traffic. When you use Ruby on Rails with React, you can reduce the server response time by up to 80%, making your apps much faster. The low speed of web apps is one of the main reasons businesses lose users.

If minimizing the server request time is your priority, you should consider Rails and ReactJS for your application.

3. Cut down memory usage 

It is a common issue for applications as they scale. If not managed correctly, increased memory usage can lead to poor performance and even timeouts. The solution lies in optimizing the memory utilization by the app. React with Rails API can be used to prevent unnecessary memory usage by optimizing processes to allocate and empty available space more efficiently. Egghead.io, an online learning platform for web developers, struggled with timeouts every hour before they decided to deploy a React with Ruby on Rails solution. It significantly improved their application’s performance and improved memory usage.

4. Development speed, quality & business model

App development is increasingly popular, driven by the increase in the use of smartphones. The ‘time to market’ is significant in a competitive domain. It simply determines how much time it will take to build and publish an application. When Rails is combined with React, you have a complete technology stack to develop and deploy apps in the least time possible. Also, if you aim to offer an app based on the freemium model, Rails works great because it’s a cheaper technology. Also, it provides additional features like scalability once your user base starts growing.

Another reason to try a combination of React with Ruby on Rails is that you can build a fully functional prototype fast. It helps you test the market and get feedback from the users to guide appropriate future decisions. However, if you aim to earn revenues from ads with a huge base of free users, you should not use Rails with React as it is not entirely a free option.

Conclusion 

Whether or not you should use React with Ruby on Rails depends on the project’s requirements. There is no straightforward answer, as the tech stack is not a universal solution but a potential combination for developing dynamic applications with innumerable micro-interactions. If you are building large scalable web applications, you need to consider the points mentioned above.

Talent500 offers app developers a platform to connect with Fortune 500 companies and fast-growing global startups. Join our elite pool of talented developers and get hired by the best tech companies by signing up here.

 

4 main reasons why React re-renders

React developers often build applications without ever giving the re-rendering process much thought. Most developers have enough understanding of React rendering to get by. To help you better understand re-rendering, our React experts created this article.  

What is a re-render in React?

React is known for its impressive performance, and it is made possible by the rendering of the objects on the screen. It happens in two major stages:

  • Initial render: This happens when a component or object first appears on the screen.
  • Re-render: Second or any consecutive render of the element already on screen.

Re-rendering occurs when React updates the app with some new data, often resulting from user interaction with the app. This is why non-interactive apps with no asynchronous data to handle never need re-render and the associated optimizations.

What is a necessary and unnecessary re-render?

Not every React re-rendering is necessary, and even not advised.

Necessary re-render is when you need to re-render a component that is the source of the changes in an app. Re-rendering is also helpful for parts that directly use any new information. For instance, a part that manages the user input’s state needs to update or re-render at every keystroke.

Unnecessary re-renders are propagated through an app due to several re-render mechanisms. It can be due to React coding mistakes or inefficient app architecture. For example, if instead of a part, the entire application page re-renders on every keystroke when a user types in an input field, the page re-rendering is unnecessary.

Fortunately, unnecessary re-renders are not an issue. React is very fast, and there is no noticeable difference in performance if some components re-render unnecessarily. However, too often, unnecessary re-rendering of weighty components can lead to poor user experience.

When does the React component re-render itself?

There are four main reasons why a React component would re-render itself:

  • State changes
  • Parent (or child) re-renders
  • Context changes
  • Hook changes

For some developers, this might not be the complete list, as React developers tend to believe that re-rendering happens when a component’s props change. That’s not entirely true, as you will know in a short while.

1. Re-renders due to state changes

A component’s state change triggers re-render. Usually, in a React code when a component either uses a callback or in useEffect hook, the state changes which is the source of re-renders in most cases.

Consider the following code:

import { useState } from “react”;

import “./styles.css”;

const App = () => {

  const [state, setState] = useState(1);

  const onClick = () => {

   setState(state + 1);

  };

console.log(“Re-render number: “, state);

  return (

   <>

    <h2>Open console, click a button</h2>

<p>Re-render because of state change should be logged on every click</p>

    <button onClick={onClick}>click here</button>

   </>

  );

};

export default App;

Here re-render happens as highlighted here:

https://www.developerway.com/assets/react-re-renders-guide/part2-state-changes-example.png

2. Re-render due to parent re-renders

A component will re-render itself if its parent re-renders and vice versa. It can also be stated that when a component re-renders, it re-renders all its children. The re-render of the components is always down the tree, i.e., if a child re-renders, it will not re-render the parent. However, there are some caveats here, and you must check out this post on React Element, children, parents, and re-renders.

3. Re-renders due to context changes

When the value of a Context Provider changes, all the components that use that Context Provider will re-render. This will happen even if the components do not use the changed value directly. These kinds of re-renders cannot be prevented with memoization directly, and React developers need to find different approaches depending on their code to stop them.

Here’s an example:

  const value = useMemo(

   () => ({

    value: state

   }),

   [state]

  );

  return (

<Context.Provider value={value}>

    <button onClick={onClick}>click here</button>

    {children}

</Context.Provider>

  );

};

const useValue = () => useContext(Context);

const Child1 = () => {

  const { value } = useValue();

console.log(“Child1 re-renders: “, value);

  return <></>;

};

const Child2 = () => {

  const { value } = useValue();

console.log(“Child2 re-renders”, value);

  return <></>;

};

const App = () => {

  return (

   <Provider>

    <h2>Open console, click a button</h2>

    <p>Both children will re-render because of context</p>

    <Child1 />

    <Child2 />

   </Provider>

  );

};

export default App;

When you run this code in the console and click the button, both children will re-render because of the Context.

4. Re-renders due to hook changes

Whatever happens within a hook is directly associated with its component. As with Context and State changes, any change within a hook triggers component re-render. Whenever the state inside the hook changes, it will trigger an unpreventable re-render of the “host” component. Also, if the hook uses Context and its value changes, the host component will be re-rendered.

Conclusion 

React re-render is an essential concept to understand for React developers. Preventing unnecessary re-renders is necessary for React app performance and efficiently utilizing resources. The listed four scenarios are how React re-renders components.

Talent500 is the global platform companies use to hire talented React developers. Sign up here and join our elite talent pool.

 

JavaScript concepts you should know before learning ReactJS

React, the most widely used JavaScript framework with over 40% market share, can be a valuable addition to your skill set. An essential thing about React is that it is fundamentally JavaScript. Hence, the better you are at JavaScript, the easier it will be for you to write quality React code.

While there are several JavaScript concepts every frontend developer must master, engineers at Talent500 picked some essential concepts that Reactjs developers should know.

Let’s break the essential JavaScript concepts you need to master React.

1. Function declarations and arrow functions 

Any Reactjs application is built using various components. React components are independent and reusable code blocks that can be defined with JavaScript classes and functions. However, React components return JSX elements, unlike JavaScript functions. 

Here’s an example of a JavaScript function: 

// JavaScript function: returns any valid JavaScript type

function javascriptFunction() {

  return “Hello world”;

}

Same with Reactjs: 

// React function component: returns JSX

function ReactComponent(props) {

  return <h1>{props.content}</h1>  

}

Here, the difference can be seen in the casing of the names of the JavaScript functions and React function components. JavaScript functions names follow camel casing, while React function components are written with pascal casing. 

In JavaScript, you can write a function in two different ways: 

Using the function keyword: function declaration

New way introduced in ES6: arrow function

You can write React components using either of the ways. However, most React developers prefer arrow functions for their brevity. You can use several shorthands when creating arrow functions. It helps remove unnecessary boilerplate, and you can write the entire code in a single line.

Here’s an example: 

// Function declaration syntax

function MyComponent(props) {

  return <div>{props.content}</div>;

}

// Arrow function syntax

const MyComponent = (props) => {

  return <div>{props.content}</div>;

}

// Arrow function syntax (shorthand)

const MyComponent = props => <div>{props.content}</div>;

2. Template literals

JavaScript has always been clumsy with handling strings, but with the arrival of ES6, it became easier to add strings together without using the + operator. You can concatenate or connect multiple strings using template literals.

You use template literals with two backticks ” instead of single or double quotes.

Here’s an example of how strings were concatenating in JavaScript before ES6:

function sayHello(text) {

  return ‘Hello ‘ + text + ‘!’; //awkward syntax

}

sayHello(‘React’); // Hello React!

With template literals concatenating strings is much simpler and creates much more readable code.

function sayHelloAgain(text) {

  return `Hello again, ${text}!`;

}

sayHelloAgain(‘React’); // Hello again, React!

The most powerful feature of template literals is the ability to use any JavaScript expression within the ${} syntax. When you master template literals, you can dynamically create strings in React.

For instance, here is a code for dynamically loading string values in head or body elements in a website:

import React from ‘react’;

import Head from ‘./Head’;

function Layout(props) {

  // Shows site name (i.e. Reed Barger) at end of page title

  const title = `${props.title} | Reed Barger`;  

   return (

   <>

    <Head>

     <title>{title}</title>

    </Head>

    <main>

    {props.children}

    </main>

   </>

  );

}

3. Async/Await

It is a better alternative to writing promises in JavaScript than the traditional method. Not only does it help write clean and clear code, but you can also convert any ordinary function into a promise by simply using the async keyword. 

Here is a React code to fetch data from a GitHub API using the Fetch API to show a profile image using promises:

/* Go to react.new and paste this code in to see it work! */

import React from ‘react’;

const App = () => {

  const [avatar, setAvatar] = React.useState(”);

React.useEffect(() => {

   /* 

    The first .then() lets us get JSON data from the response.

    The second .then() gets the url to my avatar and puts it in state. 

   */

  fetch(‘https://api.github.com/users/reedbarger’)

    .then(response => response.json())

    .then(data => setAvatar(data.avatar_url))

    .catch(error => console.error(“Error fetching data: “, error);

  }, []);

return (

   <img src={avatar} alt=”Reed Barger” />

  );

};

export default App;

The code has to use callbacks every time to resolve data from a promise. We can improve the code and use async/await to clean the syntax, like this: 

/* Go to react.new and paste this code in to see it work! */

import React from “react”;

const App = () => {

  const [avatar, setAvatar] = React.useState(“”);

React.useEffect(() => {

   /* 

Note that because the function passed to useEffect cannot be async, we must create a separate function for our promise to be resolved in (fetchAvatar)

   */

   async function fetchAvatar() {

    const response = await fetch(“https://api.github.com/users/reedbarger”);

    const data = await response.json();

    setAvatar(data.avatar_url);

   }

fetchAvatar();

  }, []);

return <img src={avatar} alt=”Reed Barger” />;

};

export default App;

Conclusion 

JavaScript is a robust language, and you might have missed some concepts when you were learning basic JavaScript. However, to become a proficient Reactjs developer, you must master these JavaScript concepts, among several others. Here are some additional JavaScript concepts that front-end developers must know.

Talent500 is the platform for elite Indian developers to discover global job opportunities. Join our select pool of talent today.

 

5 common mistakes to avoid when using React in 2022

Since Facebook released React in 2013, it has become one of the most widely used JavaScript frameworks. According to Statista, React is the world’s second most used web development framework. As the popularity of JavaScript remains high, React utilizes its capabilities to provide the most comprehensive tool sets to build web and mobile applications.

As a React developer, you have the opportunity to be part of a technology that has immense growth potential shortly. More and more web developers are adopting this JavaScript framework. Backed by Facebook and a vast developer community, React is a framework to master if you want to become a web developer.

However, there are some common mistakes that you must avoid. Here we take a look at the most common React mistakes developers commit.

1. Not creating enough components

A common mistake any React developer can make is not creating enough components. React is a highly versatile language, and if you are creating a few significant components, you’re missing its reusability. While it is not wrong to produce large components that execute many tasks, it is recommended that you create smaller components, more preferably, one component corresponding to one function. This approach saves time and is a significant benefit when debugging the code. Any errors can be easily spotted as you know which components are associated with which functions.

Here is an example of a TodoList component broken down to single functions:

// ./components/TodoList.js

 import React from ‘react’;

 import { useTodoList } from ‘../hooks/useTodoList’;

import { useQuery } from ‘../hooks/useQuery’;

import TodoItem from ‘./TodoItem’;

import NewTodo from ‘./NewTodo’;

const TodoList = () => {

  const { getQuery, setQuery } = useQuery();

  const todos = useTodoList();

  return (

   <div>

    <ul>

     {todos.map(({ id, title, completed }) => (

      <TodoItem key={id} id={id} title={title} completed={completed} />

     ))}

     <NewTodo />

    </ul>

    <div>

     Highlight Query for incomplete items:

     <input value={getQuery()} onChange={e => setQuery(e.target.value)} />

    </div>

   </div>

  );

};

 export default TodoList;

2. Modifying the state directly

Another common mistake React developers commit is modifying the state directly. As a rule of thumb, in React, the state must always be immutable; otherwise, there will be performance issues that will be difficult to fix.

Here’s a code:

const modifyPetsList = (element, id) => {

  petsList[id].checked = element.target.checked;

setPetsList(petsList);

};

Here we want to update the checked key of an object in the array based on the state of the checkbox, but there is an issue. React cannot observe and trigger the re-rendering of the object because it has been changed with the same reference.

Either you can use the setState() method or the useState() hook to fix the issue. These methods will ensure that React acknowledges the changes made to the object and that your DOM is correctly re-rendered.

3. When rendering the list, do not use the key

If you are a beginner or used our React developer toolkit to learn the language, you must have come across the prompt when you render a list according to the method described in the documentation.

For example, rendering these arrays:

const numbers = [1, 2, 3, 4, 5];

const listItems = numbers.map((number) => <li>{number}</li>);

will display this prompt on the console “a key should be provided for list items.”

The solution is obvious here. We have to follow the prompts and add the key attribute to each item like this:

const numbers = [1, 2, 3, 4, 5];

const listItems = numbers.map((number, index) => <li key={index}>{number}</li>);

The key helps React identify which elements have changed, which is why you need to assign a unique value to the key. In the above example, we have used the index as the key value.

However, we do not recommend you to use the key and ignore the prompt.

This is because the value of the key will change every time an item is added or removed from the array. It will result in performance degradation.

4. Using Redux too much

Redux is becoming very popular among React developers, primarily working on large apps. It is helpful as it helps manage global state, but you don’t have to use it to manage every state in your React apps.

If your applications do not use parallel-level components that need to exchange information, then there is no need to use Redux. Instead, you should use a local state method or useState when you use form components or want to check the state of an element every time it is accessed.

5. Incorrect use of boolean operators

In JSX/TSX syntax, React developers often use boolean values to control rendered elements utilizing the && operator like this:

const count = 0;

const Comp = () => count && <h1>Chris1993</h1>;

While we want that page to display empty content at this time, it will actually display 0 on it.

The error is because the falsy expression causes elements after && to be skipped. However, the value of the falsy expression is returned.

The correct way to write the condition without relying on the JavaScript’s boolean value to compare:

const count = 0;

const Comp = () => count > 0 && <h1>Chris1993</h1>;

Now the page will display empty content.

Conclusion 

Now that you have learned some common React mistakes, keep them into account when creating your next React app. Gradually you can inculcate these best practices and soon they will become a learned behavior and improve your code quality.

And if you are an experienced React developer, join Talent500. We are a global remote team-building platform that Fortune500 companies and fast-growing startups use to hire talent.

 

3 useful tips to clean up your React component types

React is created by Facebook to allow developers to have control over all the functions of JavaScript and have the freedom to code in any style. However, developers must follow some common patterns and conventions for reusability and maintainability. Writing clean React component code is a standardizing technique for a unified project structure.

React Components are independent and reusable bits of code that help make the code much more concise. They are similar to JavaScript functions, the only difference being that they work in isolation and return HTML. As a React developer, you will use the React component library often to write code faster and more efficiently.

This post looks at some of the best practices for writing clean React component types.

1. Write React components in TypeScript

TypeScript offers a type interface allowing developers to write better code without worrying about explicitly defining each variable type. It is the property of TypeScript to infer the style of the variable from its value. In the context of a React component, it can be used to write code without explicitly defining the variable type in the codebase. It helps clean up the component codebase.

Here is an example of how TypeScript can infer the return type of the React components without explicitly defining it; the resulting code is cleaner.

// Letting TypeScript inferring the type: (props: MyProps) => JSX.Element

const MyComponent = (props: MyProps) => <div>beep</div>;

// Explicitly defining a return type (3 similar options of writing the same as above)

const MyComponent = (props: MyProps): ReactElement => <div>boop</div>;

const MyComponent = (props: MyProps): JSX.Element => <div>boop</div>;

const MyComponent: FC<MyProps> = (props) => <div>boop</div>;

Some developers argue that using TypeScript to allow React component code to infer the return type can be risky. It is possible in more dynamic systems, so it is advised to check the inferred type to avoid making mistakes.

Since the release of React hooks in version 16.8, components can be written as functions because you can get the same functionality with much less code. The React.FC type from the @types/react package is used to mark a function as a component.

2. Use maps over if/else

When creating React components try to use maps over if/else statements wherever possible. The if/else statements create nesting within the code that makes the codebase challenging to read or maintain.

React component code can be greatly simplified with maps, and nesting can be avoided. Here is an example of a component using if/else:

const Student = ({ name }) => <p>Student name: {name}</p>

const Teacher = ({ name }) => <p>Teacher name: {name}</p>

const Guardian = ({ name }) => <p>Guardian name: {name}</p>

export default function SampleComponent({ user }) {

   let Component = Student;

   if (user.type === ‘teacher’) {

     Component = Teacher

   } else if (user.type === ‘guardian’) {

     Component = Guardian

   }

 return (

     <div>

      <Component name={user.name} />

     </div>

   )

}

The same React component when written using maps, the complexity of the code eases. Here’s how:

import React from ‘react’

const Student = ({ name }) => <p>Student name: {name}</p>

const Teacher = ({ name }) => <p>Teacher name: {name}</p>

const Guardian = ({ name }) => <p>Guardian name: {name}</p>

const COMPONENT_MAP = {

   student: Student,

   teacher: Teacher,

   Guardian: Guardian

}

export default function SampleComponent({ user }) {

   const Component = COMPONENT_MAP[user.type]

return (

     <div>

      <Component name={user.name} />

     </div>

   )

}

When you use maps, the components become more declarative and much easier for any developer to comprehend. Furthermore, it makes it easy to extend the logic or add more items to it.

3. Split larger components 

One of the best ways to write cleaner React components is to use the ‘separation of concern‘ method to split more significant components. In the context of React components, the separation of concern implies separating the parts of the components responsible for displaying the element tree from the ones responsible for fetching and mutating the data.

The hooks were introduced in React to facilitate separation of concern and allow developers to write cleaner code. In practical applications, it is used for wrapping the logic that manages API calls or global state connections with a custom hook.

Here’s an example of React component:

import React from ‘react’

import { someAPICall } from ‘./API’

import ItemDisplay from ‘./ItemDisplay’

export default function SampleComponent() {

   const [data, setData] = useState([])

useEffect(() => {

    someAPICall().then((result) => {

      setData(result)

     })

   }, [])

function handleDelete() {

    console.log(‘Delete!’);

   }

function handleAdd() {

    console.log(‘Add!’);

   }

const handleEdit = () => {

    console.log(‘Edit!’);

   };

return (

     <div>

      <div>

        {data.map(item => <ItemDisplay item={item} />)}

      </div>

<div>

        <button onClick={handleDelete} />

        <button onClick={handleAdd} />

        <button onClick={handleEdit} />

      </div>

     </div>

   )

}

Now, the same component is refactored with the code split using custom hooks:

import React from ‘react’

import ItemDisplay from ‘./ItemDisplay’

export default function SampleComponent() {

   const { data, handleDelete, handleEdit, handleAdd } = useCustomHook()

return (

     <div>

      <div>

        {data.map(item => <ItemDisplay item={item} />)}

      </div>

      <div>

        <button onClick={handleDelete} />

        <button onClick={handleAdd} />

        <button onClick={handleEdit} />

      </div>

     </div>

   )

}

Conclusion

As a React developer, understanding the ways of creating clean components enable you to write cleaner, readable, and maintainable code. It is one of the qualities we use to vet React developers when they join Talent500. For more React developer resources, check out this React developer toolkit.

We are a global remote team building platform startups, and Fortune 500 companies use. If you want to explore opportunities, join us here.

 

 

How to style using Tailwind CSS in React

React is a popular frontend UI library that is used in almost 50 million projects each month. React is supported by Facebook, has a number of notable companies, ranging from startups to Fortune 500 companies, and has dominated the web development market for more than nine years.

Due to React JS’s phenomenal growth, a variety of libraries, tools, and add-ons for styling, state management, page routing, etc. have successfully handled the limitations of the framework. As a React developer, styling your React application is typically what you’ll be doing most of the time. 

Many great libraries have been developed since the advent of CSS libraries and frameworks to make it easier for developers to create user-friendly interfaces. Though many of them (such as Bootstrap, Bulma, and Foundation) comes with predefined components, negating the need for dynamic customization, they impose design decisions that are challenging to reverse. The developer has less control over the style of the component when using prebuilt components. This is one of the reasons why Tailwind CSS is an ideal choice for front-end developers who want to have full control of the UI.

In this detailed blog, we will cover all the fundamentals that you need to know to get started with Tailwind CSS in React.

So, let’s get started!

What is Tailwind CSS?

Tailwind CSS is an open-source utility-first CSS framework that makes it easy to apply excellent styling to your React web application by choosing from the framework’s ready-made CSS classes. Tailwind CSS  gives you the creative control to create dynamic components – which means you can tweak the values of properties to make highly customizable UI components.

Tailwind CSS follows a mobile-first approach that enables developers to create web applications that are responsive. According to Npmjs, nearly 11 million projects use Tailwind CSS each month. With over 200 contributors, it is one of the most active open-source projects. One major benefit of using Tailwind CSS is that it results in a small CSS bundle by eliminating all unnecessary CSS and speeds up website loading.

Why Use Tailwind CSS?

The field of web development is vast, and new tools are constantly being developed. Developers can avoid a number of common issues by using Tailwind CSS. Simply by using the predefined class names, Tailwind assists in creating a UI that looks good.

 The following are some advantages of Tailwind:

No naming convention: Having to name classes is one of the most difficult aspects of writing custom CSS. By offering utility-based classes, Tailwind CSS seamlessly resolves those issues.

Highly customizable: Tailwind CSS doesn’t provide you with a class name that represents the entire component; instead, it provides you with a class name that represents a specific style, such as height, width, margin, etc. These utility classes can be used to create a component from scratch.

Mobile-first strategy: The Tailwind CSS framework employs a mobile-first strategy by default. It is simpler to build complex responsive layouts freely thanks to the availability of all kinds of utility classes. Utility classes can be used conditionally across a range of breakpoints like sm, md, lg, etc., which aids in creating intricate responsive layouts.

Caching: Tailwind CSS uses the same class names repeatedly, so you won’t have to load the same styles repeatedly! This shortens the time it takes for a page to load during the development phase. 

Since Tailwind CSS is a standalone framework, it can be used with virtually every current framework, including React, Angular, Gatsby, Laravel, and others.

Here, TailwindCSS will be explained using React.

Getting Started: Creating a React application

First thing first, you must have NodeJS installed on your PC in order to create a React application. You can download it from nodejs.dev

Run the following code in the terminal to confirm that NodeJS is installed.

If the version number is printed, NodeJS has been successfully installed on your system, and the code to create a React app can now be executed. To create the React application, we’ll use the build tool create-react-app. 

Run npx create-react-app on your terminal, and it will take care of the rest for you. After installation, you’ll see something like this:

This is a good start, and you can now navigate to the project folder using the command cd project_folder_name. After that, running npm start will by default display the website at http://localhost:3000.

We are now all ready to use the React application. Let’s set up Tailwind CSS in our project now. 

How to configure Tailwind CSS in React

Installing Tailwind CSS as a dependency and configuring the template path are all that are required to configure Tailwind CSS. We’ll proceed in the same manner and learn how to complete it on our own.

By running the following command, we can first add the Tailwind CSS as a dependency to our React project.

JavaScript plugins are used by PostCSS to make CSS compatible with the majority of browsers. With the help of these plugins, you can lint your CSS, support variables and mixins, transpile upcoming CSS syntax, inline images, and more.

Installing Autoprefixer and Tailwind CSS together is a requirement. It is a PostCSS plugin that uses caniuse.com values to add vendor prefixes to CSS rules automatically.

We can initialize Tailwind CSS by running the command tailwind init and it will create a default configuration file for Tailwind. After running the command, you will see a default tailwind.config.js like this:

The tailwind.config.js file needs to be updated to include all of the paths to your template files. Since we are dealing with React here, you call the files with extensions like .js, .jsx, .ts, or .tsx.

After adding the paths, you can now add the Tailwind directives to your CSS file. Add the following Tailwind layers to your CSS file, index.css in this case.

@tailwind base: It will inject Tailwind’s base styles, which combine Normalize.css and a few other base styles.

@tailwind components: This injects any component classes registered by plugins based on our config file (reusable styles like cards, buttons, form elements, etc.).

@tailwind utilities: This injects all of Tailwind’s utility classes (both the default and your customized utilities) which are generated based on our configuration file.

Now you can start your development server by running npm run start.  By styling a simple text, you can determine whether Tailwind is installed properly or not. 

                                     filename:- index.js

The output will be like this:

With just a few lines of code, we can create a small text component. You are now prepared to use Tailwind CSS in a practical setting. 

Getting Started with Tailwind CSS

There are a number of pre-built classes in Tailwind CSS that we refer to as utility classes, and we can use their class names to apply the style to the appropriate element. The majority of the class names we required for our project are present, and we can also change the default configuration to include additional styles. 

We will cover all the basics you need before starting a new project with Tailwind CSS:

Height & Width

Tailwind has several utility classes for adjusting the height and width of the element. Pixel values, percentage values and relative values are all part of it. 

We can look at a small example to visualize it.

The output will be different boxes with various heights and widths.

Padding and Margin

Tailwind has utility classes for setting margins and padding around the content that is similar to classes for height and width. You can use the values appropriately because they are almost identical to height and weight in terms of their properties, like mx-1 for margin-left: 0.25rem and margin-right: 0.25rem.

On the TailwindCSS official documentation, you can view every value that is offered.

Let’s look at a brief example where margin and padding are used.

Filename:- index.js

The output will be as follow:

CSS Flexbox and Grid

Almost all flexbox and grid properties can be defined using one of the many utility classes provided by Tailwind. Flex basics, flex-direction, flex-wrap, grid columns, grid rows, justify properties, align properties, and all other related classes are all available in Tailwind.

A simple example of CSS flexbox implementation using Tailwind CSS is shown below.

Filename:- index.js

The output will be like this:

Almost all of the design requirements are met by Tailwind’s utility classes. The framework includes utility classes for CSS properties like margin, padding, layout, sizing, typography, backgrounds, borders, filters, effects, and animations.

Responsiveness in Tailwind CSS

With Tailwind, you can create responsive designs using utility classes, just like you would for the rest of your design. There are screen-size-specific versions of each utility in Tailwind.  Tailwind by default adopts a “mobile first” strategy in which each screen size corresponds to a minimum viewport width. 

By default, five breakpoints were designed after typical device resolutions:

sm: For devices with a width of greater than 640 pixels. It represents a normal mobile phone.

md: for devices with a width greater than  768px. It represents medium size devices.

lg:  for devices with a width greater than 1024px. Usually for tablets and small laptops.

xl:  for devices with a width greater than  1280px. These are mainly for desktop monitors.

2xl: for devices whose width is above 1536px. Usually for large screen external monitors.

Although it seems straightforward, this method is actually very effective and can be used to create complex, attractive, and responsive designs.

Creating a User Card with Tailwind CSS

Now, let’s use Tailwind CSS to create and style a user card.

Filename:- index.js

When we create a responsive user card with Tailwind CSS, the desktop view looks like this:

It looks clean and tidy. Now let’s take a look at the mobile view.

Here, you can see how we were able to create an aesthetically pleasing interface using just a few lines of code, all thanks to Tailwind. You can clearly see that this method produces understandable code as compared to plain CSS.

Adding Custom Styles to TailwindCSS

Figuring out what to do when a framework isn’t able to provide for all of your needs can be difficult when using one, which is oftentimes the biggest challenge. Tailwind was created with extensibility and customization in mind, so no matter what you’re building, you’ll never feel like you’re at odds with the framework.

Add your customizations to the theme section of your tailwind.config.js file if you want to change things like your color scheme, spacing scale, typography scale, or breakpoints:

filename: tailwind.config.js

You can add custom new styles to the config file like this. Tailwind CSS offers a default theme with a very generous set of values to get you started, but don’t be hesitant to modify it or expand upon it; you’re encouraged to customize it as much as you need to meet the needs of your design. 

You can also add arbitrary values something like top-[125px], m-[19px]. This applies to everything in the framework, including pseudo-element content, background colors, font sizes, and more. You can also use square bracket notation to create totally arbitrary CSS if you ever need to use a CSS property for which Tailwind doesn’t already include a utility.

You might have realized by now, after reading this article, why Tailwind is one of the best CSS frameworks. Styling your web application is simple with TailwindCSS. 

You can always go to online communities and ask for help if you ever find yourself stuck with a problem. The Tailwind CSS team also provides prompt solutions to ensure that problems are resolved quickly. 

Tailwind CSS has created quite a stir in the technologically advanced world, but there are many other reasons too that make Tailwind the preferred choice for developers.

Wrapping It Up!

Congratulations on reaching this far! You’re a fantastic reader!!

In this detailed blog on Tailwind CSS in React, we looked at how we can make our application look beautiful and clean with Tailwind CSS. We’ve spoken about installation, customizing, and identifying the best practices with Tailwind CSS. This blog is a good start if you want to start using Tailwind in your next project.

Now you know how to style your React application with Tailwind CSS in the most effective and efficient way.

Happy Styling!

 

Getting started with web accessibility in ReactJS

React is a widely preferred frontend UI library, used in nearly 50 million projects every month. React, which is supported by Facebook, has dominated the web development market for more than nine years and boasts a number of notable clients (startups to Fortune 500 companies).

Source

Web accessibility is one of the most significant, but least considered, topics by web developers. It is simple to forget accessibility when creating new fancy web applications with React or even to forget the native features that React offers to make the website more accessible. This comes with a price to pay.

In this detailed tutorial on accessibility tools in React, we will walk you through the various methodologies through which you can make your React application accessible to everyone.

So, let’s get started!

What is Web Accessibility

Web accessibility is the practice of designing and building websites and digital tools so that people with different abilities can use them without difficulty.

A new set of accessibility features and problems have emerged as web applications become more complex and dynamic. Numerous semantic elements, such as “main” and “section,” have been added to HTML. Instead of focusing only on presentation, semantic HTML gives the web page important meaning. This makes it easier for web browsers, search engines, screen readers, RSS readers, and ultimately users, to comprehend.

A website that is accessible eliminates obstacles and guarantees that users with and without disabilities have equal access to the website’s functionality. Web accessibility also affects people with temporary disabilities, such as someone who has broken an arm, or situational limitations – such as when a person is unable to hear the audio due to loud background noise. Accessibility support is required for assistive technology to interpret web pages.

How to Make a React Application Accessible

ReactJS fully supports the creation of accessible websites, which usually make use of conventional HTML methods. You can ensure that your web application is as quickly and easily accessible as possible by following a few simple steps:

Using HTML Semantics:  

The distinguishing characteristic of a semantic element is that it makes its meaning clear to both the developer and the browser. These elements clearly define its content. 

Use semantic HTML whenever possible to make your website accessible to screen readers and to make your code more understandable. Semantic HTML tags can be used by search engines and other user devices to assess the significance and context of web pages.

Following the basic Structure

Design the interface with everything interconnected so that the user has a path to follow. In addition to structuring, headings, sections, navbars, etc. must be placed in proper locations. These semantic components serve as logical sections and improve the website’s structure.

    source

Regardless of size or complexity, an accessible semantic structure will enable accessibility on any website. Your website’s accessibility will be worse as it grows if it lacks a strong semantic foundation. Setting the right structure early in the development process helps your website stay navigable as it expands.

Keyboard Focus

When implementing accessible websites, keyboard focus is an important point to keep in mind. If you don’t make sure that keyboard focus is properly managed, users who can’t use other input methods will find it difficult to interact with your website. It is a good idea to create an outline around the input section to let the user know which input element is currently selected.

This implementation is noticeable on the Google Home page.

This can be implemented by using useRef in React so that we can access the input element and focus on it when the user clicks or hovers through the input section. The code for this is illustrated below:

Issues with keyboard accessibility on websites occur when designers or developers use techniques that go against standard keyboard functionality.

Accessible Rich Internet Applications (ARIA)

Web content and web applications can be made more accessible for people with disabilities by implementing a set of attributes called Accessible Rich Internet Applications. ARIA defines semantics for many popular UI controls so that screen readers and other assistive technologies can understand what our DOM nodes stand for.

Let’s understand ARIA with a small example.

You can see that we have provided the aria-label attribute and the screen readers know that it is a button because we used a button tag and the aria-label tells us that this button is to increment something. 

Using React Fragments

Fragments are a common pattern in React for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM. In some cases, using <div> elements in React may violate HTML semantics, resulting in difficult-to-understand page structures or invalid HTML.

Let’s look at an example where we need to use fragments:

We know that in React, we should only have one parent JSX element. If we try to wrap the list items in the above example in a <div> ,it will result in having an invalid list. In this situation, it is ideal to use fragments.

Fragments hold HTML valid and understandable, especially for users who may rely on screen reader technologies or other users who may not have access to the page’s visual elements.

Labeling

In order to make the forms accessible, labeling is used. Every HTML form control must have an accessible label. A textual label should be provided for each control.

Screen readers can better understand the context of the control they are interacting with when a label is provided. To indicate where it labels in HTML, we use the for attribute; in React, we use the htmlFor attribute. 

We have seen several ways in which we can increase web accessibility. There are some countries that have some regulations that require the website to be accessible to everyone.

Let’s now look at some of the tools that can help us identify accessibility issues in your React application.

Accessibility Tools for React Applications

Thanks to the size and constant growth of the React ecosystem, there are many tools available that can assist developers in creating web applications that are more accessible. 

Although you can detect some common accessibility issues using these tools, they won’t complete your task for you. It is your duty as a developer to make a concerted effort to create more inclusive and accessible digital products from the very beginning of the project.

eslint-plugin-jsx-a11y

To identify accessibility problems in React applications, this plugin performs a static evaluation of the JSX. Use it in combination with @axe-core/react to test the accessibility of the rendered DOM since it only detects errors in static code. Always test your apps using assistive technology, treating these tools as just one step in a larger a11y testing process.

You can make sure you are strictly adhering to some accessibility standards right away with real-time understanding if you are using an editor linting plugin. This plugin has 33 testable rules enabled, including label-has-for and alt-text.

When you use create-react-app to create a React project, it already has this tool configured, but it only has a portion of the configurable accessibility rules enabled by default. You can enable more rules by creating a .eslintrc file.

axe-core-react

The axe-core-react can be used in a React project in development to highlight accessibility issues whenever a component updates in the Chrome DevTools console.

You can run the axe-core-react plugin with the default configuration or you can add additional options.The following code shows how to run axe-core-react in your application.

react-aria-modal

It is a fully accessible and flexible React modal built according to WAI-ARIA Authoring Practices.

The React team advises using this modal library because it complies with web accessibility guidelines. It controls keyboard focus, key mapping, and ARIA roles to make sure that screen readers can access your modal.

Your component will be wrapped in a modal component that makes it simple to use, customizable, and enforces accessibility standards. This tool is extremely helpful because modals are some of the least accessible features of websites.

The axe accessibility linter VS Code extension

You can use the axe accessibility linter extension for Visual Studio Code to check React, HTML, Vue, and Markdown for some common accessibility flaws. It identifies the accessibility issues in Javascript, JSX, typescript, Vue, HTML, and markdown files.

The advantage of this extension is that it doesn’t require configuration. After installation from the VS Code Marketplace, it immediately begins linting compatible files for accessibility faults without requiring any further configuration. Installation can occasionally require a few minutes. Axe accessibility linter will start operating on compatible source files after this step is finished.

Web AIM Color Contrast Checker

According to the Web Content Accessibility Guidelines, the normal text should have a color contrast ratio of 4.5:1 for Level AA. The normal text must have a contrast ratio of 7:1 to reach Level AAA.

The two colors you’ve chosen will be analyzed by this tool, which will also provide the color contrast ratio. When creating a color scheme, you can check to see if it will go against any accessibility standards.

Google LightHouse

You can perform an accessibility audit of your website using Google’s Lighthouse Chrome DevTools. It produces a report that you can use to improve your website’s flaws.

The Google Lighthouse, like the majority of accessibility tools, evaluates web content in reference to the Web Content Accessibility Guidelines (WCAG). WCAG, which is published by the World Wide Web Consortium (W3C), is the accepted digital accessibility standard.

WAVE Evaluation Tool browser extension

You can use this additional Chrome browser extension to find accessibility problems with your website. Before using this extension to audit your web application for accessibility flaws, you must host the app. 

By adding icons and indicators to your page, it gives users a visual indication of how accessible your web content is. WAVE facilitates human evaluation and informs users about accessibility issues, but no automated tool can tell you whether your page is accessible. The browser handles all analysis, enabling secure evaluation of local, password-protected, intranet, and other sensitive web pages.

Axe DevTools browser extension

The free Axe DevTools browser extension is a fast, lightweight, yet powerful testing tool driven by the world’s most trusted accessibility testing engine, axe-core, developed by Deque.

The need for manual testing is drastically reduced when accessibility issues are proactively found and fixed using axe DevTools, giving you quick wins without slowing down development. The extension is available for Google Chrome, Mozilla Firefox, and Microsoft Edge. 

Conclusion

Congratulations on reaching this far! We are glad you read the article.

In this detailed blog on accessibility for React applications, we have covered various ways to make websites accessible. We have also discussed various best practices and accessibility tips and tricks.

Now you know how to make your React application accessible.

Happy Reacting!

 

 

3 React traps you should be wary of as a frontend developer

React is arguably the most used JavaScript framework for frontend development. It offers opportunities and options to developers that other frontend frameworks fail to deliver. For instance, React provides an easy way to handle DOM API which is usually abstracted beneath interfaces making it difficult to interact with them directly. This JavaScript framework provides developers with a virtual browser that is much more developer-friendly than real browsers. The virtual browser acts as the agent between developers and the actual browser.

React is developer-friendly in many more ways, but this article is on some common language pitfalls that developers should avoid. If you are new to React, we recommend you familiarize yourself with these React traps to avoid them easily.

Let’s see what frontend developers must know about these traps.

1. Empty data will still display 0

As a React developer, you must have written code to pull data from the server and display it as a list on the front end. If the data is empty then ideally, it must not be displayed on the screen:

Example code:

const App = () => {

  const [list, setList] = React.useState([]);

  // fetch data …

  return (

   list.length && (

    <div className=”name-list-container”>

    {list.map((name) => {

      return <div className=”name-list-item”>{name}</div>;

     })}

    </div>

   )

  );

};

However, the output of this code will display 0 when the list is an empty array. It can leave you scratching your head as to why it is doing so.

It is not a bug, but a default behavior in React caused by the operating mechanism of JavaScript itself. According to MDN docs, “in JavaScript logical AND (&&) operator (logical conjunction) for a set of boolean operands will be true if and only if all the operands are true. Otherwise, it will be false.

The AND operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.”

For example:

const a = 0;

const b = “fatfish”;

const c = 1;

const d = “medium”;

Output:

console.log(a && b); // 0

console.log(c && d); // medium

However, there are several ways to overcome this React trap. Here are some examples of how you can solve the problem by turning a into a Boolean using ternary expressions.

  1. Convert list.length to boolean

!!list.length && <Component list={list} />;

  1. Use ternary expressions and null

list.length ? <Component list={list} /> : null;

  1. Controlled by a specific logic

list.length >= 1 && <Component list={list} />;

2. Get tricked by the use of “||” and “&&” 

If you are using both AND “&&” and OR “||” operators in a statement, you have to be careful because most React developers mess up in such scenarios.

Let’s consider this code:

const App = (props) => {

  return (

   props.name || props.name2 && <div className=”user-info”>fatfish</div>

  )

}

ReactDOM.render(<App name=”medium” />, document.getElementById(‘app’))

We want to show “fatfish” when the property name or name2 is passed a value. However, the outcome will be different because the code is not working as expected.

Why?

In JavaScript, the && operator has a higher priority, which is why the above code acts like this:

const App = (props) => {

  return (

   props.name || (props.name2 && <div className=”user-info”>fatfish</div>)

  )

}

ReactDOM.render(<App name=”medium” />, document.getElementById(‘app’))

The right way to display “fatfish” when a value is passed to name or name2 is using the following code:

const App = (props) => {

  return (

   (props.name || props.name2) && <div className=”user-info”>fatfish</div>

  )

}

ReactDOM.render(<App name=”medium” />, document.getElementById(‘app’))

3. Using nested multi-layer ternary expressions

React might be robust but be careful if you use multiple ternary expressions nested in your React app. It might very well be a nightmare for you and any other developer. Such nested code is hard to read and debug.

For instance, here’s nested multi-layer ternary React code:

{

  isUserA ? (

   <ComponentA />

  ) : isUserB ? (

   <ComponentB />

  ) : (

   isUserC ? <ComponentC /> : null

  );

}

If you write React code like this, you need to change your style right now.

You can simplify the code with the use of an if-else.

Here’s the above code without nesting:

const renderCompnent = () => {

  let component = null

  if (isUserA) {

   component = <ComponentA />

  } else if (isUserB) {

   component = <ComponentB />

  } else if (isUserC) {

   component = <ComponentC />

  }

  return component

}

As you can see, with nested ternary, React code becomes easy to read. It is a skill that will serve you well in your career as your code will be easy to maintain and debug.

Conclusion 

React is here to stay, and so is JavaScript. You can stand out by mastering the nuisances of React framework that give other developers nightmares. We hope these three commonly faced React traps won’t bother you anymore.

Talent500 is the remote team-building platform Fortune 500 companies use to hire engineering talent. Join our elite pool of talent, and sign up here.