Skip to main content

Introduction to Function-based React Components

React is a JavaScript library for building user interfaces. One of the core concepts in React is the component. A component is a piece of code that represents a part of a user interface. In this tutorial, we will focus on function-based components, which are components defined as JavaScript functions.

Here is a high level overview of how to use components:

  1. Create a new component
  2. Define the component
  3. Use the component

Create a new component​

Inside the "src" directory, create a new directory called "components". Inside the "components" directory, create a new file called "MyComponent.js". This is where we will define our function-based component.

Define the component​

In the "MyComponent.js" file, import React and define a function called "MyComponent". This function should take in a single argument called "props" and return a JSX element. JSX is a syntax extension for JavaScript that allows you to write HTML-like elements in your JavaScript code. Here is an example of a simple component that displays a message:

import React from 'react';

function MyComponent(props) {
return <h1>Hello, {props.name}!</h1>;
}

export default MyComponent;

In this example, the component takes in a single prop called "name" and displays it in an h1 heading.

Use the component​

Now that we have defined our component, we can use it in our application. Open the "src/App.js" file and import the "MyComponent" component. Replace the existing JSX element with an instance of the "MyComponent" component and pass in a "name" prop.

import React from 'react';
import MyComponent from './components/MyComponent';

function App() {
return (
<div className="App">
<MyComponent name="John Doe" />
</div>
);
}

export default App;

Navigate to your browser where you react app is running and you should see a text in bold header format that reads 'Hello John Doe'