In React, naming conventions for components are important to keep your code organized, readable, and consistent. Following are the common naming conventions with examples.
1. PascalCase for Component Names
React components are typically named using PascalCase, where the first letter of each word is capitalized. This helps to distinguish React components from HTML elements, which are lowercase.
For example, following snippet defines a HelloWorld functional React component.
function HelloWorld() {
return <h1>Hello, World!</h1>;
}
You can use this component like below.
<HelloWorld />
2. File Naming Convention
It is a common convention to name the file containing the component the same as the component itself, following PascalCase. This makes it easier to find components in larger projects.
Example
File Name: HelloWorld.js or HelloWorld.jsx
Component Name: HelloWorld
3. Both Functional and Class components follow pascal case.
class UserProfile extends React.Component {
render() {
return <div>User Profile</div>;
}
}
4. Component names should be descriptive and self-explanatory.
5. Prefix Naming for Reusable Components
If you have reusable components, it’s common to add a prefix to describe their type or purpose. This is especially useful when you have components that are part of a UI library or a design system.
function ButtonPrimary() {
return <button className="primary">Submit</button>;
}
function ButtonFileUpload() {
return <button className="file-upload">Upload</button>;
}
6. Differentiate Container and Presentational Components
In some cases, it is helpful to distinguish Container and Presentational components by naming convention. Container components are responsible for logic, data fetching, etc., while presentational components focus on the UI.
// Container Component
function UserContainer() {
// Contains logic, state, and passes props
return <UserProfile name="HariKrishna" />;
}
// Presentational Component
function UserProfile(props) {
// Focuses on UI rendering
return <h1>{props.name}</h1>;
}
No comments:
Post a Comment