Ali Bayat Mokhtari
Ali Bayat Mokhtari

Reputation: 188

Passing props to the child in react native

I have two components. the App component which is the parent component and the Btn component which is the child component. How can i change the value of property text from the Btn component?

export default class App extends Component<Props> {

  constructor() {
    super();
    this.text = 'testing';
    this.onClicked = this.onClicked.bind(this);
  }

  onClicked() {
    this.text = 'changed';
  }

  render() {
    return (
        <View style = { styles.container }>
            <Text style = { styles.welcome }> { this.text } </Text>
            <Btn />
        </View>
    );
  }
}

class Btn extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Button
        title = 'Button'
        onPress = { ? }
      />
    )
  }

}

Upvotes: 1

Views: 1862

Answers (2)

devserkan
devserkan

Reputation: 17598

You are holding your text value in the wrong place. Hold it in your state. constructor runs once in the initial render and it does not run again like that. But, as a React way, if you hold your data in your state, whenever state changes your component rerenders and you see the updated data.

Then, you can pass your onClick handler to the child component and use it there. Here is the working snippet. I used class-fields so no need to write a constructor and an arrow function (no need to bind it).

class App extends React.Component {
  state = {
    text: "",
  }
  
  onClick = () =>
    this.setState({text: "foo bar" });

  
  render() {
    return (
        <div>
            <p>Text is now: { this.state.text } </p>
            <Btn onClick={this.onClick} />
        </div>
    );
  }
}

const Btn = ( props ) => (
      <button onClick={props.onClick}>Click</button>
)


ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 1

mrshl
mrshl

Reputation: 531

You can pass the parent component's onClicked function as a prop to the child component.

export default class App extends Component<Props> {

  ...

  render() {
    return (
        <View style = { styles.container }>
            <Text style = { styles.welcome }> { this.text } </Text>
            <Btn onClicked={this.onClicked}/>
        </View>
    );
  }
}

class Btn extends Component {

  ...

  render() {
    return (
      <Button
        title = 'Button'
        onPress = {this.props.onClicked}
      />
    )
  }

}

Upvotes: 1

Related Questions