Home > Back-end >  How to pass state from component to main screen in react-native
How to pass state from component to main screen in react-native

Time:04-28

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

for example

MainScreen.js

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

CodePudding user response:

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.

  • Related