How to create components in reactjs
Tuesday, January 23, 2024
React Js Components Beginners
React is a popular JavaScript library for building user interfaces. One of its key features is the component-based architecture, which allows you to create reusable and modular UI elements. In this guide, we will walk you through the process of creating a simple React component from scratch. By the end of this tutorial, you’ll have a solid understanding of how to create and use components in your React applications.
Step 1: Create Your React Project
Before we get started, make sure you have Node.js and npm (Node Package Manager) installed on your system. You can download them from the official website: https://nodejs.org/. We are also assuming you have created your React app at the start of this tutorial. If you have not you can follow this 2-minute tutorial to set up a react app with Vite.
Step 2: Clear App.jsx
Now that you have a React project set up, let’s create your first component. In React, components are typically defined as JavaScript functions or classes. For this example, we’ll create a simple functional component.
To get started we are going to first delete the example code in App.jsx and replace it with this simple template.
//App.jsx function App() { return ( <div> <h1>React Component Tutorial</h1> </div> ); } export default App;
Step 3: Clear Extra Styling in index.css
To ensure there’s no unwanted styling affecting our components, open the index.css file and delete all of its contents. Don't worry; we're keeping the file itself for future styling needs.
Step 4: Create a Components Folder
Now, let’s organize our project by creating a dedicated components folder within the src directory. This folder will house all our custom React components.
Step 5: Create Component Files
Inside the newly created components folder, create two files: MyComponent.jsx and MyComponent.css. These files will be used for your custom component. You can use the following code as a starting point for myComponent.jsx:
export default function MyComponent() { return ( <div> <h1>First Component</h1> <p>Here is more of your component</p> </div> ); }
Step 6: Adding Your Component to App.jsx
Now that you’ve created your custom component (MyComponent), let's integrate it into the App.jsx file to render it within your React application. Follow these steps:
- Open the App.jsx file in your project if it's not already open.
- Import your custom component at the top of the file. Make sure to use the appropriate relative path to locate your component
//App.jsx //Importing your component import MyComponent from "./components/MyComponent"; function App() { return ( <div> <h1>React Component Tutorial</h1> <MyComponent /> {/* This renders your custom component */} </div> ); } export default App;
3. Save the App.jsx file.
With these steps, you’ve successfully integrated your custom component MyComponent into the App.jsx file. When you run your React application, you should now see your component being rendered alongside the existing content in the App component.
Part 2: Adding Props to your Component
In this part of the tutorial, we’ll explore how to add props to your React components, making them dynamic and adaptable. Props allow you to pass data from parent components to child components, enabling you to customize their behavior and appearance.
Step 1: Modify Your Component to Accept Props
Open your MyComponent.jsx file, where you previously created the MyComponent component. To make it accept props, you can modify the component's function parameters. Make sure to also install prop-types using the command: npm install prop-types.
// components/MyComponent.jsx import PropTypes from "prop-types"; export default function MyComponent(props) { return ( <div> <h1>{props.title}</h1> <p>{props.description}</p> </div> ); } MyComponent.propTypes = { title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, };
In this code, we’ve added props as a parameter to the MyComponent function. Now, your component can receive data passed as props.
Step 2: Use the Component with Props
Now, go back to your App.jsx file or wherever you want to use MyComponent. You can use the component and provide values for the props you've defined.
// App.jsx import MyComponent from './components/MyComponent'; function App() { return ( <div> <h1>React Component Tutorial</h1> <MyComponent title="Custom Title" description="This is a component with customized props." /> </div> ); } export default App;
In this code, we’re using the MyComponent component and passing two props: title and description. You can customize these prop values to suit your needs.
Step 3: Add Default Values
To add default values to props in your React component, you can use the default assignment in the parameter of the functional component or set default values using destructuring. Here’s how you can do it:
// components/MyComponent.jsx import PropTypes from "prop-types"; export default function MyComponent(props) { const { title = "Default Title", description = "Default Description" } = props; return ( <div> <h1>{title}</h1> <p>{description}</p> </div> ); } MyComponent.propTypes = { title: PropTypes.string, description: PropTypes.string, };
In the code above, I’ve used destructuring to set default values for title and description in the props object. This way, if these props are not provided when using the component, they will default to "Default Title" and "Default Description," respectively. I've also removed the isRequired validation for these props in the propTypes declaration to allow them to be optional with default values.
Step 4: Adding Styling
In the MyComponent.css file, define CSS classes for the elements you want to style in your component. For this tutorial, let's style the container, title, and description elements.
/* MyComponent.css */ .my-component-container { background-color: #f0f0f0; padding: 16px; border-radius: 4px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); width: 300px; margin: 10px; text-align: center; } .my-component-title { font-size: 24px; font-weight: bold; margin-bottom: 8px; } .my-component-description { font-size: 16px; }
Here, we have defined three CSS classes: .my-component-container, .my-component-title, and .my-component-description. You can customize these styles according to your preferences.
Now we have to import the CSS file to our component and add apply the classes to the code
// components/MyComponent.jsx import PropTypes from "prop-types"; import "./MyComponent.css"; // Import the CSS file const MyComponent = (props) => { const { title = "Default Title", description = "Default Description" } = props; return ( <div className="my-component-container"> <h1 className="my-component-title">{title}</h1> <p className="my-component-description">{description}</p> </div> ); }; MyComponent.propTypes = { title: PropTypes.string, description: PropTypes.string, }; export default MyComponent;
Within your MyComponent.jsx file, apply the CSS classes you defined in the className attributes of the respective JSX elements.
- The className="my-component-container" applies the styles to the outer container <div>.
- The className="my-component-title" applies styles to the <h1> element.
- The className="my-component-description" applies styles to the <p> element.
Using Multiple Instances of MyComponent in App.jsx
Now, let’s use multiple instances of MyComponent within your App.jsx file. You can customize the title and description props for each instance.
// App.jsx import MyComponent from "./components/MyComponent"; function App() { return ( <div> <h1>React Component Tutorial</h1> {/* First instance of MyComponent */} <MyComponent title="Custom Title 1" description="Description 1" /> {/* Second instance of MyComponent */} <MyComponent title="Custom Title 2" description="Description 2" /> {/* Third instance of MyComponent */} <MyComponent title="Custom Title 3" description="Description 3" /> </div> ); } export default App;
In this code, we’ve added three instances of MyComponent, each with different title and description props. You can customize these props for each instance to render unique content.
Congratulations!
In this tutorial, you’ve learned how to create, use, and customize React components, which are fundamental building blocks for developing interactive web applications. You’ve explored various concepts, including defining components, passing and using props, and creating multiple instances of components. Armed with this knowledge, you can continue to build more complex and dynamic user interfaces using React. Keep practicing and exploring, and you’ll become a proficient React developer in no time. Happy coding!
Cc: Aryan Vora