8 Best Practices for Writing Clean JSX Code in React

JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. In React it is used to describe how the user interface should look like.

The full form of JSX is “JavaScript XML”. Syntax extension refers to the ability to extend the syntax of a programming language beyond its built-in capabilities

Here’s an example of JSX code:

const element = <h1>Hello, world!</h1>;

This code creates a new variable called element and assigns it a JSX expression that creates an h1 element with the text “Hello, world!”.

To render this element in the DOM, we use the ReactDOM.render() method. Here’s an example:

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

1. Use proper indentation

Proper indentation is key to writing clean, readable code. Indent your JSX elements properly to make your code easier to read and understand. Here’s an example:

const MyComponent = () => {
  return (
    <div>
      <h1>Hello, world!</h1>
      <p>This is some text.</p>
    </div>
  );
};

2. Use self-closing tags for empty elements

In JSX, you can use self-closing tags for elements that have no children. This makes your code easier to read and saves a few keystrokes. Here’s an example:

const MyComponent = () => {
  return (
    <div>
      <img src="image.png" alt="An image" />
      <input type="text" />
    </div>
  );
};

3. Use single quotes for attribute values

In JSX, use single quotes for attribute values. This makes your code consistent and easier to read. Here’s an example:

const MyComponent = () => {
  return (
    <div>
      <button className='primary' onClick={handleClick}>Click me</button>
      <input type='text' placeholder='Enter your name' />
    </div>
  );
};

4. Use meaningful variable and component names

Use meaningful variables and component names to make your code more readable and easier to understand. Avoid using short or obscure names that might confuse other developers. Here’s an example:

const UserDetails = ({ name, age, email }) => {
  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
      <p>Email: {email}</p>
    </div>
  );
};

5. Use JSX fragments for multiple elements

When you need to render multiple elements in JSX, wrap them in a JSX fragment. This helps keep your code clean and organized. Here’s an example:

In the context of programming and specifically in React, a fragment refers to a way of grouping a list of children without adding an extra node to the DOM.

const MyComponent = () => {
  return (
    <>
      <h1>My heading</h1>
      <p>Some text here.</p>
    </>
  );
};

const MyComponent1 = () => {
  return (
    <div>
      <h1>My heading</h1>
      <p>Some text here.</p>
    </div>
  );
};

In terms of functionality, both of these code snippets would produce the same result when MyComponent is rendered, with the only difference being that the first one uses a JSX fragment to group the elements, while the second one uses a <div> element as a wrapper.

6. Use defaultProps to define default props

Use defaultProps to define default props for your components. This makes your code more robust and easier to use. Here’s an example:

const MyComponent = ({ text }) => {
  return (
    <div>
      <p>{text}</p>
    </div>
  );
};

MyComponent.defaultProps = {
  text: 'Default text'
};

7. Avoid using inline styles

Avoid using inline styles in your JSX code. Instead, define styles in separate CSS files or in your component’s style prop. This makes your code more modular and easier to maintain.

If you need to define styles dynamically based on props or state, you can use the style prop to apply inline styles. However, use this sparingly and only for small changes. Here’s an example:

const MyComponent = ({ isActive }) => {
  const styles = {
    color: isActive ? 'red' : 'black',
    textDecoration: isActive ? 'underline' : 'none'
  };

  return (
    <div>
      <p style={styles}>Some text here.</p>
    </div>
  );
};

8. Keep JSX expressions simple and easy to read

When writing JSX, keep your expressions simple and easy to read. Avoid nesting too many expressions or logic in your JSX code. Instead, move complex logic to separate functions or components. Here’s an example:

const MyComponent = ({ items }) => {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>
          <a href={item.url}>{item.title}</a>
          <p>{item.description}</p>
        </li>
      ))}
    </ul>
  );
};

In this example, we’re mapping over an array of items to render a list of links. The logic for mapping over the items is kept separate from the JSX code for rendering the list, making the code easier to read and understand.

Conclusion

In this post, we’ve covered 8 best practices for writing clean JSX code in React. By following these best practices, you can write code that is easier to read, maintain, and collaborate on with other developers.

import logo from "./logo.svg";
import "./App.css";

const Use_proper_indentation = () => {
  return (
    <div>
      <h1>Hello, world!</h1>
      <p>This is some text.</p>
    </div>
  );
};

const Self_closing_tags = () => {
  return (
    <div>
      <img src="./logo.svg" alt="An image" />
      <input type="text" />
    </div>
  );
};

const handleClick = () => {
  alert("j");
};

const Single_quotes_for_attribute_values = () => {
  return (
    <div>
      <button className="primary" onClick={handleClick}>
        Click me
      </button>
      <input type="text" placeholder="Enter your name" />
    </div>
  );
};

// Use meaningful variable and component names
const UserDetails = ({ name, age, email }) => {
  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
      <p>Email: {email}</p>
    </div>
  );
};

const JSX_fragments = () => {
  return (
    <>
      <h1>My headingb</h1>
      <p>Some text here. 8</p>
    </>
  );
};

const Use_defaultProps = ({ text }) => {
  return (
    <div>
      <p>{text}</p>
    </div>
  );
};

Use_defaultProps.defaultProps = {
  text: "Default text",
};

const Avoid_using_inline_styles = ({ isActive }) => {
  const styles = {
    color: isActive ? "red" : "black",
    textDecoration: isActive ? "underline" : "none",
  };

  return (
    <div>
      <p style={styles}>Some text here.</p>
    </div>
  );
};

const App = () => {
  return (
    <div>
      <h1>Hello World!</h1>
      <Use_proper_indentation />
      <Self_closing_tags />
      <Single_quotes_for_attribute_values />
      <JSX_fragments />
      <Use_defaultProps />
      <Avoid_using_inline_styles />
    </div>
  );
};

// ReactDOM.render(<App />, document.getElementById('root'));

export default App;

Leave a Comment