What is the secret to the lightning speed at which this tag is being appended to the DOM?

Have a look at this concise sandbox that mirrors the code provided below:

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  let [tag, setTag] = useState(null);

  function changeTagState() {
    setTag(<div>I am a div</div>); //className="new"
    let divTag = window.document.querySelector(`div`);
    divTag.style.setProperty("color", "red");
  }

  return (
    <>
      <div onClick={changeTagState}>Click to change tag state</div>
      {tag}
      {/* <div onClick={alterTag}>Alter tag</div> */}
    </>
  );
}

Why does the variable divTag not return null? How is it possible for it to access and apply styles to divTag?

This is what I expected to occur in the changeTagState function:

  1. setTag is executed.
  2. It then attempts to assign a value to divTag by utilizing querySelector.
  3. Once changeTagState completes, the entire component runs again. Only then is the new value of tag added to the DOM.

Answer №1

Your interpretation is accurate, but there is a crucial detail that is often overlooked: the <div> being selected by querySelector is actually the root element, not the <div> in the setTag function. To illustrate this point further, consider what happens when you log it:

function App() {
  let [tag, setTag] = React.useState(null);

  function changeTagState() {
    setTag(<div>I am a div</div>);
    let divTag = window.document.querySelector(`div`);
    console.log(divTag);
    divTag.style.setProperty("color", "red");
  }

  return (
    <React.Fragment>
      <div onClick={changeTagState}>Click to change tag state</div>
      {tag}
      {/* <div onClick={alterTag}>Alter tag</div> */}
    </React.Fragment>
  );
}
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>

If you were to attempt using a more specific selector that only applies to the newly created div, it would indeed result in returning null:

function App() {
  let [tag, setTag] = React.useState(null);

  function changeTagState() {
    setTag(<div className='the-dynamic-div'>I am a div</div>);
    let divTag = window.document.querySelector(`.the-dynamic-div`);
    divTag.style.setProperty("color", "red");
  }

  return (
    <React.Fragment>
      <div onClick={changeTagState}>Click to change tag state</div>
      {tag}
      {/* <div onClick={alterTag}>Alter tag</div> */}
    </React.Fragment>
  );
}
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>

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

Utilizing JavaScript/jQuery to activate a Bootstrap navbar post-page load

Having trouble triggering Bootstrap's navbar with plain JavaScript/jQuery while using Bootstrap 3.3.6 and jQuery 1.11.3. The data structure provided for my application cannot be modified in terms of adding classes or ids. <ul> <li ...

Determining the height of a component in React Native

https://i.sstatic.net/VLqIb.jpg The image demonstrates the styling of the component: <TouchableOpacity style={{ height: listDataSource[item.key].isExpanded ? 500 : 140, width: widthw * 0.8, marginHorizontal: 12, backgroundColor: 'red', }} Wh ...

Incorporating external JavaScript files into a React Element

I am currently revamping my Portfolio Site to incorporate modals into one of the pages as part of the transition to a Single Page Application (SPA). The JavaScript code for these modals is stored in a "main.js" file, and the necessary tags are included in ...

Using jQuery to close a DIV with a delay

At the top of my website, I have set up an alert with a close button. The jQuery function for closing the alert is as follows: /* CLOSE ALERT BAR WITH BUTTON */ $('a.ctp-alert').click(function () { $("div.ctp-alert").slideUp(); }); While this f ...

Ensuring that jQuery(document).ready(function() contains the appropriate content

Recently, I've been attempting to integrate a javascript gallery into my WordPress site. However, I'm encountering some confusion regarding what needs to be included in the .ready(function) to successfully run the gallery. The original jQuery fun ...

Unable to modify a record using the 'findById' method and save() function while utilizing promises

I am in the process of developing a cinema application using Node.js and MongoDB with Mongoose. One specific requirement I have is to update the 'Show' model when a user places an order. The task involves adding the latest seats that were ordere ...

Applying a Webkit Scroll Bar to a specific element on the webpage

I've been attempting to apply the Scroll Bar webkit styling to a particular element but haven't had any success. Despite searching extensively, I have come across 2 threads on Stack Overflow that do not provide a solution. Most of the available ...

Problem with selecting odd and even div elements

I have a div populated with a list of rows, and I want to alternate the row colors. To achieve this, I am using the following code: $('#PlatformErrorsTableData').html(table1Html); $('#PlatformErrorsTableData div:nth-child(even)').css(" ...

Runtime.UnhandledPromiseRejection - Oops! Looks like we're trying to read properties of something that doesn't exist (specifically 'headers')

I'm facing an unexpected error that has left me puzzled. Let me walk you through what I am trying to accomplish: The task at hand involves fetching data from one API and then transmitting it to another. This process is executed as a background-funct ...

Can the state be determined by the presence of other objects in the state?

Currently, I'm delving into the world of ReactJS by constructing a personalized launch page. Brace yourself for a somewhat casual explanation. Within my primary app.js file, I've set up the initial state of the application with some data like th ...

Creating a responsive design that adapts to various image sizes

In my API response, I am receiving images of various sizes. To display these images on my HTML page, I have created a table containing 4 images. To ensure responsiveness, I have set the width of the table to 100%, each row (tr) to 100%, each cell (td) to 2 ...

Tips for Testing an Ajax jQuery Function Within the document.ready Event

I am in the process of developing a script that utilizes $.ajax to make requests for a json api. My goal is to create unit tests that can verify the results received from the ajax request. For instance, I expect the returned JSON object to contain "items" ...

Encoding a JSON representation of an HTML list where all children are displayed at each parent item

Here is the structured list that I am currently working with: function convert( name_ref ) { name_ref = name_ref + " > ol > li"; var mylist = []; $(name_ref).each(function () { if ($(this).find('> ol > li').length){ myl ...

Avoid reactivating focus when dismissing a pop-up menu triggered by hovering over it

I am currently utilizing @material-ui in conjunction with React. I have encountered the following issue: In my setup, there is an input component accompanied by a popup menu that triggers on mouseover. Whenever the menu pops up, the focus shifts away from ...

Is it necessary for an embedded YouTube video to automatically play with sound?

My current project involves developing a Web Application where the client has specified that videos must autoplay with sound when a user visits it. Here is a snippet of what I have implemented: HTML: <embed id="video1" src="" wmode="transparent" type= ...

The compatibility between MUI Autocomplete and react-hook-form is limited and may not function properly

Problem Description I am encountering various errors at different times. Specifically, when I try to select a suggested option, I receive the following error and warning messages: Material-UI: The getOptionLabel method of Autocomplete returned undefined ...

Unraveling the Mystery of jQuery AJAX Response: Where Have I Gone Astray?

$.ajax({ type: 'POST', url: 'place/add', data: { lat: 45.6789, lng: -123.4567, name: "New Place", address: "123 Main St", phone: "555-1234", review: "Great place!", cat ...

Divide a JSON dataset into two distinct JSON files and incorporate them within the code

My JSON file structure is as follows: { "rID": "1", "rFI": "01", "rTN": "0011", "rAN": "11", "sID&quo ...

Selenium is unable to locate certain elements due to the JavaScript page not being fully loaded, causing issues with implicit and explicit wait functions

Confusion reigns as I navigate through this scenario. Working with Selenium 2 in C# and the browser being IE8, our application employs JavaScript for transitioning between panels, though these transitions actually represent different pages while technica ...

Differences in outcomes have been observed between the elementLocated and findElements functions

Currently, I am in the process of developing Webdriver automation for a specific web application. As part of this process, I have created a test that seems to be functioning well most of the time but occasionally encounters an issue. it('verifies pre ...