Alex Dn
Alex Dn

Reputation: 5553

How to use existing HTML element in React?

Is it possible to reference existing HTML element in React?
I have a page where React used only for small part of components and I have "video" element that exists on page before React loads. Then I have a react component which have a couple of props that should affect video element.

What is the best/correct way to achieve this?
Currently, in render method of a component, I use document.getElementById('video-' + this.props.videoId) and then manipulating it. I thought that I can somehow use "refs" to say to reuse the existing HTML element, but not sure how and didn't found useful information.

Thanks!

Upvotes: 1

Views: 1327

Answers (1)

Saqib
Saqib

Reputation: 735

What I understand is, you have an app, probably built in some other stack and you are trying to use React inside that app. The page is loaded before and then the React component renders. As pointed out by Icepickel, refs are for the components that are created by you inside the React app. So, you can't use that here.

Normally, it is discouraged to directly access the elements in the DOM. But since you are using it on a part of it, so it is totally fine. But doing it in the render() method is not the right choice here.

Instead what you can do is, utilize the React lifecycle methods to control the video player in a better way. Normally when a component is mounted on the DOM. Following lifecycle methods are called in the following order:

  1. constructor
  2. componentWillMount
  3. render
  4. componentDidMount

So, what I will suggest is, inside the constructor set the state using document.getElementById('video-' + this.props.videoId). [I am assuming the page laods before the react component].

let el = document.getElementById('video-' + this.props.videoId);
this.state = {
  videoPlayer: el;
}

And then later when your component is mounted. Inside the componentDidMount, change whatever you want to change in the video player.

I have also created a small Code Sandbox Sample to elaborate on the lifecycle methods. This way, you will be able to write cleaner code and easily manage the state of the video player.

Upvotes: 2

Related Questions