Fire Hand
Fire Hand

Reputation: 26396

Close child component from the child component itself

I would like to close the child component from the child when user click on the close button in child component. Tried to it by passing the state from the child back to the parent but it's not working. What have i done wrong here?

Parent

class Home extends Component {
  constructor() {
    this.state = {
      visible: true
    }
  {

  closeComponent = () => {
      this.setState({
          visible: false
      });
  }

  render() {
    return (
      <Container>
       {
         this.state.visible &&
         <Child closeComponent={this.closeComponent} />
       }
      </Container>
    )
  }
}

Child

import React from 'react';
import { Text, Image } from 'react-native';
import { View, Button } from 'native-base';

import styles from './ChildStyles.js';

export const Child = ({ closeComponent }) => {
  return (
    <View style={styles.Container}>
      <Button style={styles.Btn} onClick={() => closeComponent}>
        <Text style={styles.BtnText}>Close</Text>
      </Button>
    </View>
  );
};

export default Child;

Upvotes: 0

Views: 136

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281894

The syntax for arrow function in child is incorrect. Also native-base Button doesn't have an onClick but an onPress handler. It should be

  <Button style={styles.Btn} onPress={() => closeComponent()}>
    <Text style={styles.BtnText}>Close</Text>
  </Button>

Upvotes: 1

Related Questions