This blog describes how to display Hello World! using a functional component in React.
To display “Hello, World!” using a functional component in React, you can create a simple functional component and return the desired text within JSX. For example.
import React from 'react';
// Functional component
const HelloWorld = () => {
return (
<div>
<h1>Hello, World!</h1>
</div>
);
};
export default HelloWorld;
In this example:
- We import React from ‘react’ because JSX gets translated to React.createElement() calls.
- We define a functional component called
HelloWorld
using an arrow function syntax. - Inside the component, we return JSX that represents the “Hello, World!” message wrapped in an
<h1>
element. - Finally, we export the
HelloWorld
component to make it available for use in other parts of the application.
You can then use this component in any other component or in the root of your application like so.
App.js
import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './HelloWorld';
const App = () => {
return (
<div>
<HelloWorld />
</div>
);
};
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
export default App;
In this App.js
file:
- We import React and ReactDOM as they are necessary for creating React components and rendering them into the DOM.
- We import the
HelloWorld
component from the ‘./HelloWorld’ file. Ensure that the path is correct based on your project structure. - We define a functional component called
App
using an arrow function syntax. Inside this component, we render theHelloWorld
component. - Finally, we render the
App
component inside<React.StrictMode>
usingReactDOM.render()
, which mounts the component onto the HTML element with the id of ‘root’.
This App.js
file serves as the entry point of your React application.
Make sure you have a root element in your HTML file with the id of ‘root’ where React will mount your application.
Output
Further Reading
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go
20+ Interview Questions on Go Programming Language