Adherence to coding conventions is crucial in a ReactJS project for maintaining code quality, readability, and consistency across the team. Below are key conventions and best practices that should be followed in our ReactJS projects.
  • Embrace Reusability with Components and Layouts

    Create reusable components and layouts to avoid code duplication. For example, prefer using predefined Row and Column components over divs for layout structuring.
// Example of using Row and Column components
<Row>
  <Column size={6}>{/* Content */}</Column>
  <Column size={6}>{/* Content */}</Column>
</Row>
  • Leverage SCSS for Styling Utilize SCSS for enhanced styling capabilities. This allows for more organized and maintainable stylesheets with features like nested rules, variables, and mixins.
-Employ ClassNames Package for Conditional Class Names When dealing with conditional class names, use the classNames package for readability and maintainability. Define class names in lowercase, using hyphens as spacers, and leverage the & syntax in SCSS for nesting.
import classNames from "classnames";
import "./component.scss";

const MyComponent = ({ isLoading }) => {
  const buttonClass = classNames({
    button: true,
    "button--loading": isLoading,
  });

  return <button className={buttonClass}>Click me</button>;
};
// SCSS example with & syntax
.button {
  // styles
  &--loading {
    // styles for loading state
  }
}
  • Follow TypeScript Practices for Type Safety
TypeScript should be used as the primary programming language for type safety and better development experience. Below is a basic example demonstrating a functional component in TypeScript:
interface GreetingProps {
  name: string;
}

const Greeting = ({ name }: GreetingProps): JSX.Element => {
  return <div>Hello, {name}!</div>;
};
  • Use Functional Components with Hooks
Prefer functional components over class components and leverage hooks for state management and side effects.
import React, { useState, useEffect } from "react";

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

  useEffect(() => {
    // Side effects
  }, []);

  return (
    <div>
      {count}
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

Maintain Clean and Structured Code

Ensure that your code is well-structured and commented. Proper indentation, consistent naming conventions, and clear function definitions are essential.

Utilize Predefined Methods and Components

Always refer to the project documentation for predefined methods and components that can expedite your development process. Utilizing available resources ensures consistency and efficiency. By following these coding conventions, developers can ensure that their ReactJS projects are robust, maintainable, and scalable, facilitating a smooth development process and collaboration across the team.