Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

79
Views
How to get state of children from parent in class component

I'm trying to display the state of child component in parent component, but somehow the text "abcde" still not show, here is the sample code

import React from 'react';
import {SafeAreaView, StyleSheet, Text} from 'react-native';
import {TouchableOpacity} from 'react-native-ui-lib';

class ChidComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
    };
  }
  render() {
    return (
      <SafeAreaView>
        <TouchableOpacity
          onPress={() => {
            this.setState({text: 'abcde'});
            this.props.getText(this.state.text);
          }}>
          <Text>Get Text</Text>
        </TouchableOpacity>
      </SafeAreaView>
    );
  }
}

const style = StyleSheet.create({
  text: {
    fontWeight: 'bold',
    fontSize: 40,
  },
});
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
    };
  }
  getTextFromChild(value) {
    this.setState({text: value});
  }
  render() {
    return (
      <SafeAreaView>
        <Text>{this.state.text}</Text>
        <ChidComponent
          getText={this.getTextFromChild.bind(this)}
          press={() => this.setState({show: !this.state.show})}
          textStyle={style.text}
        />
      </SafeAreaView>
    );
  }
}
export default ParentComponent;

But somehow the screen still empty, the 'abcde' still until i click twice, come from functional component so i don't know what going on, please help, thank you a lots

7 months ago · Santiago Gelvez
1 answers
Answer question

0

Your getTextFromChild method in the ParentComponent is removing the show property from the state, update it to this:

 getTextFromChild(value) {
    this.setState({text: value, show: true });
  }

EDIT: setState is async, you can pass a callback function as an argument to access the updated state.

   <TouchableOpacity
          onPress={() => {
            this.setState({text: 'abcde'}, () => {
              this.props.getText(this.state.text);
           }); 
   }}>

Should work.

7 months ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.