React Native get value from a child component

Viewed 134

I have two simple components :

const AddUserInfo = () => {

    const scroll = useRef(null)


    return (

        <View style={ styles.container }>
            <View style={ styles.slider }>
                    <ScrollView
                    ref={scroll}
                    horizontal= {true}
                    snapToInterval= {width}
                    decelerationRate= "fast"
                    showsHorizontalScrollIndicator= {false}
                    bounces= {false}
                    >

                    <Animated.View style={{flex: 1, width: width }}>
                    <Slider1 style={{flex: 4}}/>
                        <Animated.View style={{flex: 2, justifyContent: 'flex-end', alignItems: 'center'}}>
                            <TouchableOpacity style={styles.buttonCircle} onPress={() => { 
                                if(scroll.current) {
                                    scroll.current.scrollTo({ x: width, y: 0, animated: true });
                                    }
                                }}/>
                        </Animated.View>
                    </Animated.View>

and this one :

const Slider1 = () => {

    const [pseudo, setPseudo] = useState("")



    return (
        <Animated.View style={{flex: 4}}>
            
                <TextInput
                mode="outlined"
                value={pseudo}
                label="Pseudo"
                placeholder="Pseudo"
                onChangeText= {(pseudo) => setPseudo(pseudo)}
                />
            
        </Animated.View>
    )
}

In order to keep everything clean, they are in different files. What i'm trying to do here is to get the 'pseudo' value from the Slider1 component and being able to use it into the AddUserInfo component.

What is the best way to do it ?

Thanks for your help !

2 Answers

You can pass a callback function in the parent component to the child, then in the child component call that callback function and pass the value to the parent

In this example:

Parent:

<Slider1 style={{flex: 4}} onChangeValue={(value) => { /* do sth with the value */}}/>

In child component

<TextInput
            mode="outlined"
            value={pseudo}
            label="Pseudo"
            placeholder="Pseudo"
            onChangeText= {(pseudo) => {
                setPseudo(pseudo)
                this.props.onChangeValue(value)
            }}
            />

The most straightforward solution is to have your Slider component accept a callback prop which is called on state change which is passed the updated pseudo value.

const { useState, useRef, useEffect} = React;

function App() {
  const [input, setInput] = useState('');
  
  const sliderCallback = (v) => {
    setInput(v);
    console.clear();
    console.log(`Slider changed to: ${v}`);
  }
  
  return (
    <div>
    <Input callback={sliderCallback} />
    <p>{input}</p>
    </div>
  )
}

function Input({callback}) {
  const [pseudo, setPseudo] = useState('');
  
  useEffect(() => {
    callback(pseudo);
  }, [pseudo])
  
  return (
    <input type='text' onInput={(e) => (setPseudo(e.target.value))} /> 
  )
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

<div id='root'></div>

Related