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
?
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.
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.
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>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With