Tips on assigning a reference to an element that has not been rendered yet

I've created a login page with a button labeled "Watch the video". When the button is clicked, it hides and reveals a video player. My goal now is to automatically start playing the video once it's displayed without requiring an extra play button click. I've tried using refs but can't seem to set the ref for the video element properly. Is there a way to set refs for elements that are not rendered in componentDidUpdate? Any assistance would be greatly appreciated! Here's my code:

export default class NewLoginPage extends Component {
  constructor(props) {
    this.vidRef = React.createRef();
    this.state = {
      showVideo: false
    };
  }
    
  handleVideoClick = () => {
    this.setState({ showVideo: true })
    this.vidRef.current.play();
  }
    
  handleCloseClick = () =>{
    this.setState({ showVideo: false })
  }
    
  render() {
    let language_labels = labels["english_labels"]
    console.log(labels)
    console.log(language_labels)
    return (
      <div className="container-fluid no-padding">
        <div className="new-login-div">
          <AppBar className="app-bar">
            <Toolbar className="tool-bar">
              <img src={pmiLogo} />
            </Toolbar>
          </AppBar>
          <Grid container>
            <Grid item xs={4}>
              <h1 className="welcome-heading">Self Service Portal</h1>
              <TextField
                className="id-field"
                placeholder="Email"
                inputProps={{
                  style: {
                    color: "#fff",
                    paddingLeft: "5px"
                  }
                }}
              />
              <br />
              <Button className="login-btn" endIcon={<ArrowForwardIcon />}>Log In</Button>
            </Grid>
            <Grid item xs={8}>
              <div className="video-div">
                {this.state.showVideo && <div>
                 <IconButton className="close-btn" onClick={(event) => this.handleCloseClick()}>
                   <CloseIcon />
                 </IconButton>
                 <video ref={ref => { this.vidRef = ref }} width="500" height="285" controls className="video-container">
                   <source src={exampleVid} type="video/mp4" />
                   Your browser does not support the video tag.
                 </video>
               </div>}
               {!this.state.showVideo && <div className="intro-div">
                 <h5 className="intro-text">
                   Supporting the vitality and survival of US small businesses—who employ nearly half of the American workforce—is especially critical now. Let’s not forget just how essential they are.
                 </h5>
                 <Button
                   disableRipple={true}
                   className="video-button"
                   startIcon={<PlayArrowIcon className="play-icon" />} onClick={(event) => this.handleVideoClick()}
                 >
                   Watch video
                 </Button>
                 <br />
                 <Button
                   disableRipple={true}
                   className="reg-button"
                   startIcon={<ChevronRightIcon className="play-icon" />}>
                   Register
                 </Button>
               </div>}
             </div>
           </Grid>
         </Grid>
       </div>
     </div>
   );
  }
}

Answer №1

With React, the ref property allows access to a DOM element's reference.
However, if the element is not rendered, the DOM element is not created or deleted.
Therefore, you cannot obtain a reference to something that does not exist.

Answer №2

To achieve this, you can simply add the autoplay html property to your <video> tag without needing a ref. Find more information on autoplay here

Trying to use a ref on an element that hasn't been rendered yet, as explained by Anton in his response, will result in ref.current being null.

It's recommended to separate the logic for the video component from the login component. Not only does this solve the issue (keeping the this.state.showVideo condition in the parent component), but it also aligns with React best practices. For more insights, check out this article.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I make an image disappear after animation with CSS?

I experimented with this code snippet in an attempt to fade out an image, .splash-wrapper { animation: fadeIn 4s; -webkit-animation: fadeIn 4s; -moz-animation: fadeIn 4s; -o-animation: fadeIn 4s; -ms-animation: fadeIn 4s; animation-duration: ...

Warning: Close button position is unmanageable

This is what the alert and close button should look like on my website, based on Bootstrap's design. However, after implementing it into my site, it ended up looking like this. I attempted to modify the bootstrap.min.css file, but the changes did not ...

Extract the URL parameter and eliminate all characters following the final forward slash

Here is the URL of my website: example http://mypage.com/en/?site=main. Following this is a combination of JavaScript and PHP code that parses the data on the site. I am now looking for a piece of code that can dynamically change the URL displayed in the ...

Ways to implement useState in a TypeScript environment

Hello, I am currently using TypeScript in React and trying to utilize the useState hook, but encountering an error. Here is my code: import React , { useState } from "react"; interface UserData { name: string; } export default function AtbComponent( ...

Displaying items in the shopping cart across two separate columns

I have a website located at Within that page, I have included the Cart table using a woocommerce shortcode. Currently, the cart table is positioned below the billing details and payment options section. My goal is to move this cart table to be situated ...

Tips on using htmlspecialchars in combination with a href:To safely include links in

If I have the following code: $text = "please visit this <a href='http://example.com'>site</a>." $text = htmlspecialchars($text); echo $text; The output will be please visit this <a href='http://example.com'>site< ...

traverse a deeply nested object within an array

Currently facing an issue with mapping over an array containing multiple nested objects. The map function seems to only return the outer object when executed. https://i.stack.imgur.com/7JNsN.png const [moreDetails, setMoreDetails] = useState([]); const [d ...

What is the best way to integrate React and Node.js in a single project?

Recently, I have run into a minor issue. I am aware that I can build a react-app using npm run build to create an optimized build folder for production use. However, after incorporating node.js into my react application some days ago, I am now uncertain ab ...

Set the CSS table to have a width of 100% and ensure that the table data cells have hidden

My table has a 100% width, and some of the td elements have overflow hidden. I want to make their text appear as ellipsis when it's too long. I can achieve this with fixed td sizes, but I need them to be relative to the content. This question was fi ...

"Steer clear of using `useEffect` to fetch data upon mounting if the dependency relies on user input

When a React component mounts, the useEffect hook is triggered. However, if this effect relies on user input, running it on mount might be unnecessary. In such cases, would it be acceptable to validate the dependency before executing the hook? Check out t ...

After deploying my next.js app on cPanel, it suddenly displays a blank screen

I recently deployed my Next.js app on cPanel and encountered a blank screen issue, although it works perfectly fine when tested locally. Here's the detailed process I followed: 1. To begin with, I created a custom server.js file in the root directory ...

CSS - fixed table headers

Check out my CodePen example here - Code In this demo, I have a table inside a container where the table is larger than the container. As you scroll horizontally, both the table and headers move accordingly. However, when scrolling vertically, I want th ...

Developing a PHP foreach loop that integrates seamlessly with a W3 responsive grid

Is there a way to generate multiple sets of three columns using w3.css and a foreach loop to fill each set with data from a sample database? Attempted code resulted in all the columns being in a single row: <?php foreach ($products as $index => $pro ...

Executing a function when clearing an autocomplete textfield in Material-UI

Currently, I am working with a material-ui autocomplete text field in order to filter a list. My goal is to have the list repopulate back to its original form when the user deletes the text and presses the enter key. After my research, it seems like the ...

Utilizing distinct useState for mapped elements

I am struggling to find a solution on how to pass specific useState states to respective mapped elements. export const Polska = () => { const [riverVisible, setRiverVisible] = useState(false) const [mountainVisible, setMountainVisible] = useState(fa ...

Tips for centering text in the Accordion Component of Material-UI

Here is my customized Accordion component: https://i.stack.imgur.com/Pz8CE.png I am trying to center align the headings (Accordion 1, Accordion 2) in the above component but struggling to do so. Could someone please provide guidance? Below is the code s ...

Error: The navigation property is not defined - React Native

Utilizing Firebase in combination with react-native for user authentication. The main file is App.js which directs users to the Login component and utilizes two components for managing routes: Appnavigator.js to create a switchNavigator and DrawerNavigator ...

What methods can be used to validate an undefined value?

exploding right now if (myObject.myKey.myThing){ } undefined myThing cannot be read What approach can be taken to determine if myThing is defined before entering the if block? ...

What is the best way to send multiple values from the view to a method without using two-way binding?

When I change the dropdown value for the route type in my code, I need to pass both the gender value and the route type ID to my data retrieval method. Currently in my HTML file, I have only written a change event. I attempted two-way binding but encounte ...

Utilizing Typescript, create a customized dropdown with react-bootstrap for a tailored user

I've been working on incorporating a custom toggle drop-down feature based on the example provided on the react-bootstrap page, using Typescript and react functional components. Below is the code snippet for my component: import React from &apos ...