Adam
Adam

Reputation: 55

how to update a component from another child component in ReactNative

Right. I've been googling for days and can't seem to find an example that works and that I understand.

I've currently got three components, ButtonComponent, SecondButton, and TextComponent.

I already have it such that tapping Button can update State and thus change the text in TextComponent (if i set setState to the text string on line 39).

How can I change it so that it will change to a string of text that I can set from the button itself rather than the function fired by the button, so that SecondButton can fire the same function as Button, but update the text to something different.

I figure it must be a small tweak to onPress? but everything I try keeps complaining about objects and things being undefined.

Thanks.

import { setStatusBarNetworkActivityIndicatorVisible, StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';


function ButtonComponent({changeText}) {
  console.log(`2. ${changeText} from inside Button Component`)
  return(
    <Button title="change text" onPress={changeText} />
  )

}

function SecondButton({changeText}){
  return(
  <Button title="change text again" onPress={changeText} />
  )
}

function TextComponent({text}) {
  console.log(`3. ${text} from inside Text Component`) //
  return (
    <View>
      <Text style={styles.text}>{text}</Text>
    </View>
  )
}

export default function App() {
console.log('1 .start')

const [text, setText] = useState('default text'); // declared in the screen

const changeText = ({newtext}) => {
    setText(newtext)
    console.log(`4. ${text} just after changeText`)
  }

  return(
   <View style={styles.container}>
     <ButtonComponent changeText={changeText}/>
     <SecondButton changeText={changeText}/>
      <TextComponent text={text}/>
    </View>
  )
}



const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    color: 'red',
  }
});

Upvotes: 1

Views: 172

Answers (1)

RamaProg
RamaProg

Reputation: 1387

function SecondButton({changeText}){
  return(
  <Button 
    title="change text again" 
    onPress={() => changeText( { newtext: "different string" })}
  />
  )
}

Upvotes: 1

Related Questions