How to useFunctional Components in ReactJS

To access properties from parent to child using a functional component, users don’t need to use ‘this.props‘ like class components. Users can access props value by writing variable names only.

Steps: 

  1. Embed the child component to the parent component.
  2. Pass the props to the child component as an argument while embedding it to the parent component.
  3. In the child component, access the data variable value by writing the name or variable only.

Example:

Javascript




// FileName - App.js
 
import React, { Component } from "react";
import Child from "./components/child.js";
 
// Parent component
// Embedding child component inside it
function App() {
    return (
        <div>
            <h1>This is a parent component</h1>
            <ul>
                <li>
                    <Child
                        gfgcolor="green"
                        usercolor="blue"
                    />
                </li>
            </ul>
        </div>
    );
}
 
export default App;


Javascript




// FileName - components/child.js
 
import React, { Component } from "react";
 
// Passing props as a parameter
// inside the child component
export default function Child({ gfgcolor, usercolor }) {
    return (
        <div>
            <h1>This is a child component</h1>
            <h1 style={{ color: gfgcolor }}>
                w3wiki
            </h1>
            <h1 style={{ color: usercolor }}>
                Welcome to Ggf!
            </h1>
        </div>
    );
}


Step to run the application:

Step 1: Open the terminal and type the following command. 

npm start

Output: This output will be visible on http://localhost:3000/ in the Web browser.



How to pass property from a parent component props to a child component ?

Passing props from parent to child in React JS is an important concept. Props are read-only properties that are sent from the parent components to the child components. We can pass props in from parent to child using React JS functional as well as class components

Table of Content

  • Passing Property Using Class Components
  • Passing Property Using Functional Components

Steps to create the application:

Step 1: The below command will help you to start a new React app.

npx create-react-app testapp

Step 2: Next, you have to move to the ‘testapp‘ project folder from the terminal.

cd testapp

Step 3: Create a new components folder inside the src folder and create one component named child.js inside the component folder.

Project Structure:

Similar Reads

Approach 1: Using Class Components

...

Approach 2: Using Functional Components

When users pass the data from parent to child using the class components, they can access inside the child component using ‘this.props.property_name‘....

Contact Us