ronnie burns
ronnie burns

Reputation: 230

react js trigger function from any other component

I have a component that basically loads a video in an overlay using JW Player (simplified example below).

import React, { Component } from 'react'
import ReactJWPlayer from 'react-jw-player'

class VideoPopup extends Component {

render() {
    return (            
        <div id="video">
            <ReactJWPlayer 
              playerId='video-player'
              playerScript='https://content.jwplatform.com/libraries/vr6ybmGf.js'
              file='path to video file'
            />
        </div>

    )
  }
}

export default VideoPopup;

I would like the component to sit directly in the root of my app, but I need to be able to display it when called from ANY other component - this might be a child component, a child of a child, a sibling etc. etc. I was hoping to be able to call it and pass the video file reference simply like below:

<button onClick={somehow show video popup}>show video popup</button>

I understand how to do this easily if there is a direct parent-child relationship, but not if I want to place the link in a variety of different components; I hope someone can point me in the right direction.

Upvotes: 0

Views: 4128

Answers (3)

Amit Chawla
Amit Chawla

Reputation: 44

Multiple ways to do this

  • You can define a function that controls the show/hide functionality of the video player in the app component itself and pass it down as a prop to all the components where the event can be fired.
  • Use Redux. This is the ideal choice. You just have to dispatch an action from anywhere in your app and the corresponding reducer will take care of the functionality.
  • Using a global function (not recommended).

Please comment if you need more explanation.

Upvotes: 1

Mike Kor
Mike Kor

Reputation: 876

You can try to make global function and call it wherever you want.

showVideoPopup () {
    ReactDOM.render(
        <VideoPopup />,
        document.getElementById('popupHolder')
    );
}

Upvotes: 0

JulienD
JulienD

Reputation: 7293

If you want to get rid of the parent-children relationships when it comes to actions, use an event manager like Redux (react-redux). It is pretty standard an becomes necessary as your app grows anyway.

The principle is that wherever you place your link, it will fire an "action" on click, which is sent to a global dispatcher that other components listen to for changes.

Upvotes: 3

Related Questions