How to Create a Component in React
By Codes With Pankaj
A component in React is a reusable piece of code that controls a part of the user interface (UI). In this tutorial, we’ll guide you through creating your first React component.
What You Need
A React app set up (use
npx create-react-app my-app
).A text editor like VS Code.
Basic knowledge of JavaScript and HTML.
Step-by-Step: Creating a Component
Step 1: Understand React Components
React components are of two types:
Functional Components: The simplest, written as JavaScript functions.
Class Components: More complex, written using ES6 classes (rarely used in modern React).
In this tutorial, we’ll create a Functional Component.
Step 2: Create a New File for the Component
Inside your React app, go to the
src
folder.Create a new file called
Greeting.js
.
Step 3: Write the Functional Component
Open
Greeting.js
and write the following code:Explanation:
function Greeting()
: This defines a functional component namedGreeting
.return()
: Returns the JSX (HTML-like code) that will be displayed.export default Greeting
: Makes this component available for use in other files.
Step 4: Use the Component in App.js
Open the
src/App.js
file.Import the
Greeting
component:Use the
Greeting
component inside theApp
component:Explanation:
<Greeting />
: This is how you use (render) a React component inside another component.
Step 5: Start Your App
Run the app to see your new component in action:
In the browser, you’ll see:
Congratulations! 🎉
You’ve successfully created and used your first React component! Components are the building blocks of any React application, and you’ll use them to create amazing UIs.
Last updated