wafa.A
wafa.A

Reputation: 101

React Native change the state on child component

I am wondering if there is a way to update a state in a parent functional component from a child component using a function, i want to assign the value of {item} in child component to the state in parent component, i think i did that in wrong way

the parent class components:

class Home extends Component {
  state = {
    year: '',
    month: '',
    day: '',
  };
  render() {
       <Dropdown 
                 label= {i18n.locale == 'en' ? 'Year' : 'سنة'} 
                 data={years} 
                 onSelect={() => this.setState(year)}/>
}

the child component:

const Dropdown = ({ label, data ,onSelect}) => {
     const renderItem = ({ item }) => (
    onSelect={() => this.setState(item )} 
   <TouchableOpacity style={styles.item} onPress={() => onItemPress(item)}>
      <Text style={styles.buttonText}>{item}</Text>
    </TouchableOpacity>
  );

}

Upvotes: 0

Views: 60

Answers (1)

PhantomSpooks
PhantomSpooks

Reputation: 3540

Think of it like this: onSelect will be the bridge between your parent component this.setState and your child component. To do that and be flexible, onSelect should have at least one parameter. Judging from what you have, it looks like you only want Dropdown to update year:

 render() {
   <Dropdown 
     label= {i18n.locale == 'en' ? 'Year' : 'سنة'} 
     data={years} 
     onSelect={year => this.setState({year})}/>
  }

Now in your child component think of onSelect as a function to call when it wants to update the year value in the parent component:

const Dropdown = ({ label, data ,onSelect}) => {
  const renderItem = ({ item }) => (
    <TouchableOpacity
      style={styles.item}
      onPress={() =>{
       onItemPress(item);
       onSelect(item);
      }
    >
      <Text style={styles.buttonText}>{item}</Text>
    </TouchableOpacity>
  );
}

Also just out of curiosity, is there reason why the parent component is a class?

Upvotes: 1

Related Questions