samedi 6 octobre 2018

React, control several 2 components from one parent component

I have one Audio and one Video that I want to play at the same time from the Parent component.

import React, { Component } from "react";

class VideoPlayer extends Component {
  state = {};

  render() {
    return (
      <video muted>
        <source src={this.props.sourceVideo} type="video/mp4" />
      </video>
    );
  }
}

class AudioPlayer extends Component {
  state = {};

  render() {
    return (
      <audio>
        <source src={this.props.sourceAudio} type="audio/mpeg" />
      </audio>
    );
  }
}

class Parent extends Component {
  state = {};

  playBoth() {
    // What else?
  }

  render() {
    return (
      <div>
        <VideoPlayer sourceVideo="video.mp4" />
        <AudioPlayer sourceAudio="soundtrack.mp3" />
        <button onClick={this.playBoth} />
      </div>
    );
  }
}

export default Parent;

What's the "react way" of achieving this?

I know that in react, data flows down. So If I get it right, I should:

  • Have a playVideoHandler() in the parent component, and pass it to the child Component: <VideoPlayer playVideo={this.playVideoHandler}/>.

  • In the VideoPlayer component, pass a reference to the <video> element, to the props.sourceVideo function. That will bring me back to my parent component where I'll handle the logic.

My questions are:

  • What's the point of having components if in the end you end up passing everything back to the parent component..?

  • Am I even thinking the whole thing right? Should I even split them into 2 components if in the end they are to be played at the same time?

Aucun commentaire:

Enregistrer un commentaire