Make a New Component
With your application set up, you are ready to make your first component.
Creating a Component
- Create a directory called
components
withinsrc
. - Inside
components
make a new file calledHello.jsx
- Write a function called
Hello
that does not have any parameters and returns a<div>
that contains one<p>
tag that just says “Hello World!”. - At the front of your function declaration add
export default
. This will allow us to import it into other files.
At this point, your Hello.jsx
file should look something like this:
export default function Hello() {
return(
<div>
<p>Hello World!</p>
</div>
);
}
Components can only return one parent element of HTML. If you look at the code above, the <div>
is the parent element and <p>
is the child element. If we placed the <p>
tag outside of the <div>
tag, we would get an error and the app would not run. As you add more and more HTML to a component, make sure that your code only has one parent element!
Calling Your Component
If you ran your app, you wouldn’t see your new component. Time to change that by calling it in the App
component.
Refactoring default App.jsx
- Inside
src
, locateApp.jsx
.
The default App.jsx
file will look like the following code block:
|
|
Remove all highlighted lines as shown above and add the following code below:
Add an
import
statement to the top ofApp.jsx
importing your component from the correct file. In this case, yourimport
statement would look like:import Hello from "./components/Hello"
.Inside the
App()
function, within the<div>
tags, add the following line:<Hello />
At this point, your App.jsx
component should look something like this:
import { useState } from 'react'
import './App.css'
import Hello from "./components/Hello";
function App() {
return (
<>
<div>
<Hello />
</div>
</>
)
}
export default App
Run your application using npm run dev
to see your rendered component!