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

The information is failing to display properly within the mat-menu

Recently, I've been working on creating a navbar that includes a submenu. Even though the navigation bar data is loading properly, I am facing some issues with the submenu functionality. As a beginner in this area, I would appreciate any help or guida ...

Guide on displaying a document in react-doc-viewer from a protected API endpoint in either Next.Js or ReactJs

I am looking to display files in my Next.JS web application using a secure API. The API provides the following data: { "name": "Test1.docx", "contentUri": "https://api.mypurecloud.ie/api/v2/downloads/x ...

Conditionally inject snippets of styling based on the emotion styling approach

I have a styled component: const StyledBox = styled(Box)(({theme, locked}) => ({ width: theme.spacing(2.5), height: `calc(50% - 12px)`, borderColor: grey[500], borderStyle: 'solid', borderWidth: 0, borderLeftWidth: 3, ...

Evaluating Material UI Radio Checked Value

I have created a functional component in React that utilizes Redux with React Hooks. For testing, I am using Jest along with Enzyme. The component contains Material UI Radio buttons which are rendered as shown in the code snippet below: <RadioGroup> ...

How can I target only one mapped item when using onClick in React/NextJS?

Apologies if this question is repetitive, but I couldn't find a better way to phrase my issue. The code in question is as follows: const [isFlipped, setFlipped] = useState(false); const flip = () => { if (!isFlipped) { setFlipped(tr ...

Typescript error points out that the property is not present on the specified type

Note! The issue has been somewhat resolved by using "theme: any" in the code below, but I am seeking a more effective solution. My front-end setup consists of React (v17.0.2) with material-ui (v5.0.0), and I keep encountering this error: The 'palet ...

What is the best way to maintain parameters in PHP form code?

I am facing an issue with a script that needs to run with a specific parameter (for example, details.php?studentid=10325). The script contains a form with the following code snippet to send form data back to the current script. However, for some reason, t ...

Complete alignment of several elements in a horizontal scrolling container

In the table-like container, I have elements with horizontal scrolling. Each element has the same width but potentially different heights. I want to add a button in the top-right corner of each element without it disappearing when scrolling. I came across ...

It is not possible to submit a form within a Modal using React Semantic UI

I am working on creating a modal for submitting a form using React semantic UI. However, I am encountering an issue with the submit button not functioning correctly and the answers not being submitted to Google Form even though I have included action={GO ...

Why isn't this code for hiding the animation and displaying it not functioning properly?

Why isn't this animation from display none to block working properly? The initial code appears as follows, and it functions correctly: $(".box_outer").stop().animate({top: '25px' , opacity: 1}, 100); When I add display: none; to the class ...

Tips for modifying layout and concealment of content when using window.print()

Currently, on my web application, the vendor is able to print the invoice using windows.print(). However, in the print preview, it displays a screenshot of the current page. The vendor has specific printed paper with their own details and some blank space ...

Is there a way to generate a distinctive curved design using CSS for a

I am currently using CSS and div elements in an attempt to create these particular lines: https://i.stack.imgur.com/Ytowq.png .line { width: 1px; height: 100px; background-color: black; position: absolute; border-radius: 50%/100px 1 ...

Is there a way to filter an array of dates without using the map function when a click

After finally grasping how to pass and retrieve data in React, I encountered an issue. I have a click handler called this.SortASC, and when I click on the title, I want to sort the titles alphabetically. However, I'm having trouble getting this functi ...

What could be causing the Universal Code for Disqus to not function properly?

Struggling to get this code to work on my website. I've tried everything, from clearing caches and cookies to disabling plugins and extensions, but still no luck. Check out the code below: import React, { Component } from 'react' import { ...

Guide on implementing asyncWithLDProvider from Launch Darkly in your Next.js application

Launch Darkly provides an example (https://github.com/launchdarkly/react-client-sdk/blob/main/examples/async-provider/src/client/index.js) showcasing how to use asyncWithLDProvider in a React project (as shown below). However, I'm struggling to integr ...

Issue in Next.js 13: Byte index exceeds limits when running 'npm run dev' command

When attempting to install Next.js 13.4.12, I utilized the command npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385b4a5d594c5d15565d404c1559484878090b160c1609">[email protected]</a>. The installation process ...

Encountering an issue when using the Google authentication provider with Next.js version 13

I am currently working on integrating next-auth with the Google provider and Prisma in my Next.js application, but I encountered the following error: Error: Detected default export in '/MyProject/foodbrain/app/api/auth/[...nextauth]/route.ts'. Pl ...

What is the best way to run a function within an if statement without duplicating code if the condition is false?

When working with relay mutation code, I find it necessary to reload the store in order for it to sync with the database. This is because if the text being added is the same as previously added text, the relay store throws an error called flattenChildren.. ...

Exploring the contrast between window and document within jQuery

I'm curious about the distinction between document and window in jQuery. These two are commonly utilized, but I haven't quite grasped their differences. ...

Utilize images stored locally in ReactJS

My path to the image is: ../src/assets/images/img_name.jpg" And my path to the file.js is: src/file_name.js If I include the following code in file.js: Import img_name from "../src/assets/images/img_name.jpg" Then reference the image pa ...