Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data between functional components in React?

In React we can pass data between class based components using states and props in the following manner:

App.js

import Name from './Name';
import React, { Component } from 'react'


export class App extends Component {
  state = {
    name: "Tarun"
  }

  render() {
    return (
      <Name name={this.state.name}/>        
    )
  }
}

export default App

Name.js

import React, { Component } from 'react'

export class Name extends Component {
    render() {
        return (
            <div>
                My name is : {this.props.name}
            </div>
        )
    }
}

export default Name

But now since React has introduced functional components what is the equivalent code if I use functional components for both App.js and Name.js?

like image 312
Tarun Khare Avatar asked Oct 02 '19 12:10

Tarun Khare


People also ask

How do you send data between functional components in React?

First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.

How do you pass a function from one component to another in react JS?

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component.


1 Answers

Using hooks you could write something like this.

In App:

import React, { useState } from 'react'

export default function App() {

  // `useState` returns an array with the state
  // and the method used to update the state
  // You can initialise the state with a variable/object
  const [name, setName] = useState('Tarun');

  // No need for a render method
  // Just return the JSX from the function
  return <Name name={name} />;
}

In Name:

import React from 'react'

// Props are passed down like normal function args
// Destructure `names` from the props object
export default function Name({ name }) {
  return <div>My name is: {name}</div>;
}
like image 129
Andy Avatar answered Sep 17 '22 19:09

Andy