DEV Community

Cover image for How to Write Cleaner React Code
Mithun
Mithun

Posted on • Edited on

How to Write Cleaner React Code

1) Functional Component with Props:

jsx

// ItemList.js

import React from 'react';

const ItemList = ({ items }) => {
return (

    {items.map((item) => (
  • {item.name}
  • ))}

);
};

export default ItemList;
In this example, we've created a functional component ItemList that takes a items prop, which is an array of objects. We use destructuring in the function parameter to access the prop.

2) PropTypes:

To document the expected types of props, you can use PropTypes:

jsx

import PropTypes from 'prop-types';

ItemList.propTypes = {
items: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
})
).isRequired,
};
This code defines PropTypes for the ItemList component, specifying that items is an array of objects with id and name properties.

3) Conditional Rendering:

If you want to conditionally render items based on a prop, you can use a ternary operator:

jsx

const ItemList = ({ items, showItems }) => {
return (

    {showItems ? items.map((item) => (
  • {item.name}
  • )) :
  • No items to display
  • }

);
};
Here, we conditionally render items based on the showItems prop.

4) CSS and Styles:

Let's define a CSS module for styling the component:

css

/* ItemList.module.css */

.item-list {
list-style: none;
padding: 0;
}

.item {
margin-bottom: 8px;
}
Apply the styles in your component:

jsx
Copy code
import React from 'react';
import styles from './ItemList.module.css';

const ItemList = ({ items }) => {
return (

    {items.map((item) => (
  • {item.name}
  • ))}

);
};

5) Code Formatting and Linting:

Ensure your code is properly formatted using Prettier, and use ESLint to enforce coding standards.

6) Error Handling:

Add error handling for props, and if the items prop is missing or empty, you can display an error message or fallback UI within the component.

7)Testing:

Write unit tests for your component using a testing library like Jest and React Testing Library. Here's a simple test example:

jsx

import { render } from '@testing-library/react';
import ItemList from './ItemList';

test('renders a list of items', () => {
const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
];

const { getByText } = render();
expect(getByText('Item 1')).toBeInTheDocument();
expect(getByText('Item 2')).toBeInTheDocument();
});
These examples demonstrate clean coding practices in React, including the use of functional components, PropTypes, conditional rendering, CSS modules, code formatting, linting, and testing. When you write your Medium article, you can explain each of these practices in more detail and provide a complete, real-world example for readers to follow.

Top comments (0)