Create functional component in new file Hello.jsx
In this step, you will create your first React component. It's a common practice to place each component in its own file to keep the code organized and reusable. We will create a new file for a component named Hello.
First, let's get the development environment ready. The project files have been created for you in the my-app directory. You need to navigate into this directory, install the necessary dependencies, and start the development server.
Open a terminal in the WebIDE (you can use the menu: Terminal > New Terminal) and run the following commands one by one:
cd my-app
npm install
npm run dev -- --host 0.0.0.0 --port 8080
After running the last command, the development server will start. You can view the running application by clicking on the Web 8080 tab in the LabEx interface. Throughout this lab, you can switch to this tab to see your changes.
In the WebIDE file explorer on the left, navigate to the my-app/src directory. Right-click on the src folder and select "New File". Name the new file Hello.jsx.
Now, add the following code to your newly created my-app/src/Hello.jsx file. This code defines a simple functional component.
function Hello() {
return <h1>Hello from the Hello component!</h1>;
}
Let's break down this code:
function Hello(): This is a standard JavaScript function. In React, functional components are just JavaScript functions. By convention, component names always start with a capital letter.
return <h1>...</h1>;: The function returns JSX. JSX (JavaScript XML) is a syntax extension for JavaScript that looks very similar to HTML. It's what we use to describe what the UI should look like.