doulouM
doulouM

Reputation: 41

Pass datas from child to parent component using Hooks

I would like to pass myVarible from Child component and retreive it in App (parent) component then put it on initialLang property.

Parent :

imports ...

// Here there is not "class App extends React.Component {" !!!

const App = () => (
    <Provider store={store}>
        <I18n translations={translations} initialLang="en" fallbackLang="en"></I18n>
    </Provider>
);

export default App;

Child :

imports ...

// Here there is not "class Child extends React.Component {" !!!

const ChildInner = ({context}) => (  
    {
        <View style={{flexDirection: "row"}}>   
            <Picker 
                onValueChange={(itemValue, itemIndex) => {
                    if ( itemIndex == 0 ) {
                        myVariable = 'en';
                    } else if ( itemIndex == 1 ) {
                        myVariable = 'fr';
                    }
                }} 
            >
                <Picker.Item label="English" value="en" />
                <Picker.Item label="french" value="fr" />
            </Picker>
        </View>
    }
);

const Child = (context) => (
    ...
);

Child.propTypes = {
    ....
};

Child.contextTypes = {
    t: PropTypes.func.isRequired,
};

export default Child;

I dont know how to use props or state for do that when using hooks. Thanks for your help.

Upvotes: 0

Views: 50

Answers (1)

Taha Dekmak
Taha Dekmak

Reputation: 21

In PARENT:

const [myVariable, setMyVariable] = useState('');
<ChildElement setMyVariable={setMyVariable}/>

In the Child

onClick={() => {props.setMyVariable('test123')}}

Upvotes: 1

Related Questions