Creating Your First Program in React Step by Step Guide

0
Creating Your First Program in React Step by Step Guide


Creating Your First Program in React

In this tutorial, we’ll create our first React program by setting up a basic component called "Hello" and displaying it on the screen through the main App.jsx component. Components in React help us organize our code into reusable sections. Let’s start step-by-step!

Step 1: Create a "components" Folder

In the src folder, create a new folder named components. This folder will hold all the reusable components we’ll create. Keeping components in their own folder helps keep the project organized.

Step 2: Create a "Hello" Component File

Inside the components folder, create a file named Hello.jsx. Each component in React must have a filename that starts with an uppercase letter (e.g., Hello, MyComponent) and uses a .jsx extension, which stands for JavaScript XML.

Code for Hello.jsx


// Hello.jsx
// This is our first component, which returns a simple heading

// Define the Hello component
function Hello() {
  // Return a heading with our message
  return <h1>Hello, React!</h1>;
}

// Export the component so we can use it in other files
export default Hello;

Explanation:

  • We import React at the top of the file, which is necessary to use JSX.
  • We create a function called Hello that returns an <h1> element with the text “Hello, React!”.
  • Finally, we use export default Hello to make this component available to other files.

Step 3: Import and Use the Hello Component in App.jsx

Now, we’ll use the Hello component in App.jsx. This is our main component that renders all other components in the application.

Code for App.jsx


// App.jsx
// Main component where we import and use the Hello component

import Hello from "./components/Hello"; // Import the Hello component we created

function App() {
  return (
    <div>
      {/* Render the Hello component */}
      <Hello />
    </div>
  );
}

export default App;

Explanation:

  • In the App.jsx file, we first import React to use JSX syntax.
  • We then import the Hello component using the path "./components/Hello".
  • Inside the App function, we render the Hello component by writing <Hello />.

How It Works

When we run the app, the App component renders Hello inside a <div>, displaying “Hello, React!” on the screen.

Final Step: Run the Project

To see your component in action, open a terminal and use the following command:


npm run dev

This command starts the development server, and you should see “Hello, React!” displayed on the screen in your browser.

By following these steps, you’ve created a simple React component and displayed it in the main application. Components like this are the building blocks of any React application, and understanding them will help you build larger projects with ease.


How to Install React.js with npm, bun, and Vite

Post a Comment

0Comments

Post a Comment (0)