Functional Component
What is a Component in React?
Components are the building blocks of any React application. They are the basic units of any React application. They are like functions that accept some input and return some HTML.
Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML.
Components come in two types:
- Function components
- Class components
We will learn about function components in this article.
In older React code bases, you may find Class components primarily used. It is now suggested to use Function components along with Hooks, which were added in React 16.8. There is an optional section on Class components for your reference.
Function components are the simplest type of component. They are functions that return some HTML.
Why use components?
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.
How to create a function component?
Function components are just functions that return some HTML. Here is an example:
This is just to give you an idea of what function components look like.
Don't create files and folders for this example. We will create them in the next section. Just focus on the code.
Here is a simple function component named MyComponent that returns <div> with some text inside it that is passed as a prop:
src/components/MyComponent.jsx
Created a new folder named components in the src folder and created a file named MyComponent.jsx in it.
export default function MyComponent(props) {
return <div>{props.message}</div>;
}
We can also use arrow functions to create function components. Here is an example:
const MyComponent = (props) => <div>{props.message}</div>;
export default MyComponent;
Now, we can use this component in our App component. We can import the component and use it in our App component.
src/App.jsx
import MyComponent from "./MyComponent";
export default function App() {
return (
<>
<MyComponent message="Hello World!" />
<MyComponent message="Goodbye World!" />
</>
);
}
You may have noticed components are just a function that returns some HTML, and use it as a tag in JSX. For example, if I created a component named MyComponent, I can use it as <MyComponent /> in JSX.
You can also create and use function components in the same file. Here is an example:
src/App.jsx
function App() {
const MyComponent = (props) => <div>{props.message}</div>;
return (
<>
<MyComponent message="Hello World!" />
<MyComponent message="Goodbye World!" />
</>
);
}
This is a live code editor. You can edit the code and see the changes in the preview.
What is a prop?
In React, "props" is short for "properties", which are values that you can pass down from a parent component to a child component. Prop is an object that contains all the properties passed to the component, i.e. the attributes of the component.
Props allow you to pass data from one component to another without the need for global variables or other forms of data sharing. This is because each React component is designed to be independent and self-contained, and it should only know about the data that it needs to render its part of the UI.
Here's an example of how props work in React:
// Parent Component
function ParentComponent() {
const name = "Rizwan Ashiq";
// Child Component
function ChildComponent(props) {
return <div>Hello, {props.name}!</div>; // Hello, John!
}
return (
<>
<ChildComponent name="John" />
<ChildComponent name={name} />
</>
);
}
In this example, the parent component passes the name variable down to the child component as a prop. The child component receives the name prop as an argument in its function and renders it in the UI using JSX syntax.
Components can be called as many times as you want, and each time you call them, you can pass different data as props. This is how you can reuse components and make them dynamic.
Props are read-only, which means that a child component can't modify its props directly. Instead, if a child component needs to change its behavior based on new data, it should receive updated props from its parent component, triggering a re-render of the child component with the new data.
Using props makes it easy to build reusable components that can be used in different parts of your application, passing in different data each time. This is one of the main reasons why React is so popular, and it helps to keep your code organized and maintainable.
We can pass functions, arrays, and objects as props from parent to child components. We will see this in the next section.
Example - Greeting App
A normal react app has a lot of components. Let's create a simple greeting app to understand how components work.
In this app, I will create only one component named Greeting which will take a prop named timeOfDay and display a greeting message based on the value of the prop. For now, I will create the component in the App component itself. Normally, we will create a new file for each component.
src/App.jsx
function App() {
function Greeting(props) {
return <h2>Good {props.timeOfDay}!</h2>;
}
return (
<div>
<Greeting timeOfDay="morning 🌅" />
<Greeting timeOfDay="night 🌃" />
<Greeting />
</div>
);
}
Example - Counter App
In this app, I will create a counter that will display the current count, and buttons to increment, decrement, and change the count by a specified amount. It will create a new component for each of these functionalities and use them in the App component.
Here are the components I will create:
CounterText- displays the current count.IncrementButton- increments the count.DecrementButton- decrements the count.ChangeByAmount- changes the count by a specified amount.
In the App component, I will use these components. I will also use the useState hook to keep track of the count. I will create functions to handle the increment, decrement, and change by the amount in App component.
First of all, let's create the components.
CounterText
This component will display the current count.
export default function CounterText({ count }) {
return <span>{count}</span>;
}
I can name arguments anything generally developers name as the prop CounterText(prop). We can also do Object destructuring to get the props from the props object. Like this: CounterText({ count }), and then we can use count in the component, like this: <span>{count}</span>. Instead of <text>{props.count}</text>. If you don't know Object destructuring, you can learn more about it here.
IncrementButton
This component will increment the count.
export default function IncrementButton({ handleClick }) {
return <button onClick={handleClick}>+</button>;
}
DecrementButton
This component will decrement the count.
export default function DecrementButton({ handleClick }) {
return <button onClick={handleClick}>-</button>;
}
ChangesByAmount
This component will change the count by a specified amount, using text input, and a button to submit the change.
export default function ChangesByAmount({ handleClick }) {
return (
<form onSubmit={handleClick}>
<input type="number" name="number" placeholder="Change by Amount" />
<button type="submit">Change by amount</button>
</form>
);
}
App
This component will use the components above to display the counter.
import React from "react";
import CounterText from "./components/counterText";
import DecrementButton from "./components/decrementButton";
import IncrementButton from "./components/incrementButton";
import ChangesByAmount from "./components/changesByAmount";
export default function App() {
// Declare a new state variable. I will pass it as a prop to the CounterText.
const [count, setCount] = React.useState(0);
// I will pass this function to the `IncrementButton` component as a prop.
const handleDecrementButtonClick = () => {
setCount(count - 1);
};
// I will pass this function to the `DecrementButton` component as a prop.
const handleIncrementButtonClick = () => {
setCount(count + 1);
};
// I will pass this function to the `ChangeByAmount` component as a prop.
const handleChangeByAmountButtonClick = (event) => {
// prevent the default behavior of the form submit event, which is to refresh the page.
event.preventDefault();
// checking if the input is a number
const amount = parseInt(event.target.number.value);
if (!isNaN(amount)) {
setCount(count + amount);
}
// resetting the input field
event.target.number.value = "";
};
return (
<div>
<DecrementButton handleClick={handleDecrementButtonClick} />
<CounterText count={count} />
<IncrementButton handleClick={handleIncrementButtonClick} />
<ChangesByAmount handleClick={handleChangeByAmountButtonClick} />
</div>
);
}
Code
You can get the code for this doc here
Conclusion
In this tutorial, we learned about function components and props. We also learned how to use components in our application. We also learned how to pass data to components using props.