Skip to content Skip to sidebar Skip to footer

React Different Ways Of Calling A Child Method

React says we should not use refs where possible and I noticed that you can't use shallow rendering testing with refs so I have tried to remove refs where possible. I have a child

Solution 1:

Rather than call child functions, try to pass data and functions down from the parent. Alongside your component, you can export a wrapper or higher order function that provides the necessary state / functions.

let withMedia = Wrapped => {
  return class extends React.Component {
    state = { playing: false }
    play() { ... }
    render() {
      return (
        <Wrapped 
          {...this.state} 
          {...this.props} 
          play={this.play}
        />
      )
    }
  }
}

Then in your parent component:

import { Media, withMedia } from 'your-library'

let Parent = props =>
  <div>
    <button onClick={props.play}>Play</button>
    <Media playing={props.playing} />
  </div>

export default withMedia(Parent)

Solution 2:

Keep the state as localized as you can, but don't spread it over multiple components. If you need the information whether it is currently playing in both the parent and the child, keep the state in the parent.

This leaves you with a much cleaner state tree and props:

class Child extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.props.togglePlay}>Child: Play/Pause</button>
        <p>Playing: {this.props.playing ? 'Yes' : 'No'}</p>
      </div>
    );
  }
}

class Parent extends React.Component {
  constructor(props) {
    super(props);
    
    this.togglePlay = this.togglePlay.bind(this);
    
    this.state = {
      playing: false
    };
  }
  
  togglePlay() {
    this.setState({
      playing: !this.state.playing
    });
  }
  
  render() {
    return (
      <div>
        <button onClick={this.togglePlay}>Parent: Play/Pause</button>
        <Child togglePlay={this.togglePlay} playing={this.state.playing} />
      </div>
    );
  }
}

ReactDOM.render(
  <Parent />,
  document.getElementById('app')
);
<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='app'></div>

Post a Comment for "React Different Ways Of Calling A Child Method"