Issue with React rendering numbers without displaying div

In my user interface, I am attempting to display each box with a 1-second delay (Box1 after 1 second, Box2 after another 1 second, and so on).

https://i.sstatic.net/FdTkY.png

However, instead of the desired result, I am seeing something different:

https://i.sstatic.net/9zpE2.png

Please review my React code below and help me identify where I may have gone wrong, resulting in the unexpected output showing numbers alongside the boxes:

const CreateBox = (props) => {
  return (
    <>
    {/*<div className="box">{props.num}</div>*/}
    <div className="box"></div>
    </>
  )
} 

const App = () => {
  return (
    <div className="app">
      <h3>App</h3>
      {
        [1,2,3,4,5,6,7,8,9,10].map((item) => {
          return setTimeout(() => {
            // return (<CreateBox num={item} />)
            return (<CreateBox />)
          }, 1000)
        })
      }
    </div>
  )
}

const root = document.querySelector('#root')
ReactDOM.render(<App />, root)

View on Codepen - https://codepen.io/anon/pen/pBLPMY

Answer №1

To avoid creating a new timeout for each element in the array every time it renders, consider setting up an interval in the `componentDidMount` method and incrementing a counter in your state until it reaches a certain value. You can then use this counter in your render method.

Here's an example:

class App extends React.Component {
  state = {
    count: 0
  };

  componentDidMount() {
    const interval = setInterval(() => {
      this.setState(
        ({ count }) => ({ count: count + 1 }),
        () => {
          if (this.state.count === 10) {
            clearInterval(interval);
          }
        }
      );
    }, 1000);
  }

  render() {
    return (
      <div className="app">
        <h3>App</h3>
        {Array.from({ length: this.state.count }, (_, index) => (
          <CreateBox key={index} num={index + 1} />
        ))}
      </div>
    );
  }
}

const CreateBox = props => {
  return <div className="box">{props.num}</div>;
};

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Answer №2

Avoid using setTimeout within a loop; it's better to place the timer inside the CreateBox component by utilizing state. When you eliminate the timeout, the boxes become visible. To control the delay, assign the index * 1000 as a timer for each element.

Answer №3

class GenerateSquare extends React.Component {
  state = {
    opacity: 0
  }

  constructor(props){
    super(props)
  }
  
  componentDidMount(){
    setTimeout(()=> this.setState({opacity: 1}),`${this.props.time}000`)  
  }
  
  render() {
    console.log(this.props)
    return (
      <div style={this.state} className="square">{this.props.num}</div>
    )
  }
};

const App = () => {
  return (
    <div className="app">
      <h3>App</h3>
      {
        [1,2,3,'w',5,6,7,8,9,10].map((item, index) => <GenerateSquare num={item} time={index}/>)
        
      }
    </div>
  )
}

const target = document.querySelector('#root')
ReactDOM.render(<App />, target)

Answer №4

function generateBoxes(props) {
  return (
   <div className="box">{props.num}</div>
  )
} 

function displayApp() {
  return (
    <div className="app">
      <h3>App</h3>
      {
        [1,2,3,4,5,6,7,8,9,10].map((item) => {              
             return (<generateBoxes num={item} />)
        })
      }
    </div>
  )
}
const root = document.querySelector('#root')
ReactDOM.render(<displayApp />, root)

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

Is there a way to use HTML to prevent the user from navigating away from the current page when submitting a form? Could jQuery, PHP, or a combination of

Is it achievable to send a message using PHP and keep the user on the same page after clicking "Send Message" button? Perhaps changing the submit button to a success message on the following page: . Can this task be accomplished with PHP and jQuery? ...

Utilize Moment to round a date either up or down

I am using Moment to compare two datetime values. Specifically, I am utilizing Moment.isSameOrBefore function. However, my two date values are slightly different due to milliseconds. I want these two values to be considered the same: var date1 = ' ...

Having issues with nth-child? It seems like nth-of-type isn't working either

I am trying to change the color of all even titles from h2 to orange using nth-child. However, I seem to have made a mistake somewhere and can't figure out what it is... *{ font-size: 1em; } h2{ font-size: 1.5em } ...

Utilizing HTML5 Drag and Drop feature to track the initial position of the element being dragged

Currently, I am utilizing the HTML 5 Drag and Drop API to create a sortable list with auto scroll functionality. One crucial aspect I am trying to incorporate is the ability to detect which specific part of an element was grabbed by the user. Take a look ...

What could be causing the issue with the functionality of third-level nested SortableJS drag-and-drop?

I am currently utilizing SortableJS to develop a drag-and-drop form builder that consists of three types/levels of draggable items: Sections, Questions, and Options. Sections can be dragged and reorganized amongst each other, Questions can be moved within ...

Ensure that the text is wrapped properly when implementing innerHTML functionality

Within my Angular 5 application, I am faced with a requirement to display HTML content retrieved from a database. An example of the text stored in the database is: <div><u>Documents and Files</u></div><ul><li>These docu ...

Guide on sending a key to a text input field using JavaScript

How can I simulate sending a combination of keys (such as Ctrl+C or Alt+Shift) when the cursor enters an input text field using Javascript? I am not utilizing jQuery, but rather MS-Ajax. Is it achievable with MS-Ajax DOM? EDIT 1) Following @Ghostoy&apos ...

Are there any available tools or scripting methods for accommodating various vendor prefixes?

My preference is to use standard CSS rules for different styles that include various vendor prefixes. To test, I would start with the following: border-radius: 5px; box-shadow: 0px 0px 4px 0px #fff; transform: rotate(90deg); For the final version, I woul ...

Can I fetch the visible rows (along with their order) from a React Material-table?

I've recently started working with React and I'm utilizing a special component known for its unique filtering functionality that I couldn't find elsewhere. This component typically shows 10 rows of data by default. Whenever I apply filters ...

Is there a way to choose multiple IDs in this code that all share a common word?

I'm attempting to target several duplicate ids such as "img1, img2" in my code, but I haven't had any success. How can I select all the ids that contain the same word without relying on jQuery or any other external libraries? Below is the code s ...

Vue.js - Implementing multiple values (array) for a component through a property

I am currently working with vue.js components that receive their data from external sources. For example: <vue-button icon="fa-arrow-right" text="mytext"></vue-button> Initially, this setup is effective. However, I encountered a challenge wh ...

Create a nested array of subcategories within an array object

Currently, I am working on integrating Django Rest and Angular. The JSON array received from the server includes category and subcategory values. My goal is to organize the data such that each category has its related subcategories stored as an array withi ...

The constant reloading of the page is hindering the crucial display of the data

After successfully getting something to work, I noticed that the data disappears when the page refreshes. How can I prevent this from happening? <html> <head> <meta charset="utf-8"> <title> IT Services </ti ...

Tips for identifying a scroll down gesture on a touch device with jQuery

I have a method for infinite scroll that is triggered like this: $(window).on('scroll resize load', function() { // execute the infinite scroll method }); It is triggered by these events: scroll resize load However, it does not seem to ...

Font family 'anticon' is not recognized

While following a coding tutorial on YouTube, I encountered an error message that has me stumped. Despite having the correct import statement and dependency installed, the issue persists. Error message in iOS simulator: https://i.stack.imgur.com/LOVCQl. ...

Show a table when a button is clicked using Javascript

Undertaking a project called: Tennis Club Management involving javascript, HTML, CSS, and bootstrap. The project includes a Login Page (index.html) and a Manage Players Page (managePlayers.html). Within the managePlayers.html, there are two buttons - Add P ...

Validate input strings in Node.js using Joi to detect and return an error if there are leading or trailing spaces

Looking to set up JOI validation in Node.js that flags errors if a string begins or ends with an empty space. For example: name = "test123" //valid name = "test(space)" or "(space)test" // invalid ...

Encountering a JS error that states: "Uncaught SyntaxError: missing ) after argument list" when running the following code

I keep encountering the error message: "Uncaught SyntaxError: missing ) after argument list" when I try to call the delete function within the createHtmlview function. console.log("Delete Item is being called") } ...

Identifying elements in @mui/material and @mui/labs

Encountered difficulty when attempting to utilize components from external libraries @mui/material and @mui/labs. Below is the code used: import { Box, Tab } from '@mui/material' import { TabContext, TabList, TabPanel } from '@mui/lab' ...

Difficulties encountered when preserving the data of a website in HTML format

Usually, I request tweets on Twitter for a specific period and then scroll down the page to the last tweet. I save the HTML code of this page by right-clicking and selecting "Save As..." However, only the latest tweets are displayed in this HTML file. Is ...