Home > OS >  How to pass Value between two component in React Native?
How to pass Value between two component in React Native?

Time:01-20

I am learning React Native from scratch and stuck into an issue. I get a name in the profile component from the user and store it into AsyncStorage correctly. Now, I'd like to use the name in other components, but I can not pass the data between the two components.

CodePudding user response:

It's better to send your code here. But below ways may help you.

How to Pass Data Between a Parent Component and a Child Component Firstly, let's pass data between a parent component and a child component.

First, you'll need to create two components, one parent and one child.

    import React from 'react'

    export default function Parent() {
    return (
    <div>
      
    </div>
  )
}

Parent.js

 import React from 'react'

     export default function Child() {
    return (
        <div>
            
        </div>
     )
    }

Next, you'll import the child component in the parent component and return it.

    import React from 'react'
    import Child from './Child';

    export default function Parent() {
    return (
    <div>
      <Child/>
    </div>
   )
   }

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.

import React from 'react'
import Child from './Child';
import { Button } from 'semantic-ui-react';
import { useState } from 'react';
import './App.css';

export default function Parent() {
  const [data, setData] = useState('');
  
  const parentToChild = () => {
    setData("This is data from Parent Component to the Child Component.");
  }
  return (
    <div className="App">
      <Child/>
      
      <div>
        <Button primary onClick={() => parentToChild()}>Click Parent</Button>
      </div>
    </div>
  )
}

read more

CodePudding user response:

You could just read it from another component using AsyncStorage. There is no need for passing here.

  •  Tags:  
  • Related