fuzzy buddy
fuzzy buddy

Reputation: 119

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

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

Upvotes: 1

Views: 376

Answers (1)

Or&#231;un G&#252;ler
Or&#231;un G&#252;ler

Reputation: 118

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.

Upvotes: 2

Related Questions