Vinicius Morais
Vinicius Morais

Reputation: 595

How change a state variable via props?

I'm trying do show a modal screen with a button, when i press the button the modal will appears. The variable that is responsable for it is modalVisible and its a variable state. But if my button is not in the same class of my screen Profile i'm not able to change the variable, at last i dont know a way to do:

class Carrousel extends React.Component {
  render () {
    return (
      <Button
        title= 'press me to show up'
        onPress= {() => this.props.visible = true}
      />
    );
  }
}

export default class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: true,
    };
  }
  render() {
    return (
      <View>
        <Modal
         visible = {this.state.modalVisible}>
        </Modal>
        <Carrousel visible = {this.state.modalVisible}/>
      </View>
    );
  }
}

Is there an way to change this variable modalVisible in another class? Or is there another way to i show the modal with a button in another class?

*The carrousel class is another file Carrousel.js.

Upvotes: 0

Views: 481

Answers (1)

Alberto
Alberto

Reputation: 1408

You have to set a function as a prop that changes the state on the Parent Component. I haven't tried but it should be something like this:

class Carrousel extends React.Component {
  render () {
    return (
      <Button
        title= 'press me to show up'
        onPress= {() => this.props.setVisible()}
      />
    );
  }
}

export default class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
    };
    this.setVisible = this.setVisible.bind(this);
  }

  setVisible() {
    this.setState({
      modalVisible: true,
    })
  }

  render() {
    return (
      <View>
        <Modal
         visible = {this.state.modalVisible}>
        </Modal>
        <Carrousel setVisible={this.setVisible}/>
      </View>
    );
  }
}

Upvotes: 1

Related Questions