Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass state from component to main screen in react-native

I’m having trouble passing state from a component to main screen in react-native

for example

MainScreen.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const MainScreen = () => {
  return (
    <>
     <AdButton/>
     <Text>{adCreated}</Text>
    </>

  )
}

AdButton.js

 const [adCreated, createAd] = useState(false);

 const adButton = () => {
   createAd(true);
 }

 const AdButton = () => {
   return (
     <TouchableOpacity onPress={adButton}>Create an Ad</TouchableOpacity>
   )
 }

How can I have the state of adCreated show true on MainScreen when the state is changed in the AdButton Component.

Thanks,

Arnav

>Solution :

To do so you need to lift the state up If your use case does not include a mapping of these items just declare the state in the main component and pass it as a prop to the children.

Edit:

const MainScreen = () => {
  const [adCreated, createdAd] = useState(false);
  return (
       <>
         <AdButton createdAd={createdAd}/>
         <Text>{adCreated}</Text>
       </>

      )
    }


const AdButton = ({createdAd}) => {
   
    return (
      <TouchableOpacity onPress={createdAd((prev) => !prev)}>Create an Ad</TouchableOpacity>
   )
 }

As per your request you can follow this type of behavior when trying to accomplish this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading