0

I'm new in React App, i just want to create DIVs after each clicking the button, please help.

import logo from './logo.svg';
import './App.css';


function App() {
  function handleSubmit() {
    let div = document.createElement('div');
    div.innerText = document.getElementById('getText').innerText;
    document.body.appendChild(div);
    }
  return (
    <div className="App">
      <header className="App-header">
      <form onSubmit={handleSubmit}>
       <button>Click me!</button>
       <div id="getText"> INNER TEXT</div>
       </form>
      </header>
    </div>
  )}


export default App;

1 Answer 1

1

Keep a state on the number of times you click the button (count). Then you can use a for loop to create how many number of div you need to add.

import { useState } from "react";

const divCreator = (total) => {
  const divArray = [];
  for (var i = 0; i < total; i++) {
    divArray.push(
      <div id="getText" key={i}>
        INNER TEXT
      </div>
    );
  }
  return divArray;
};

function App() {
  const [count, setCount] = useState(0);

  function handleSubmit() {
    setCount((state) => state + 1);
  }
  return (
    <div className="App">
      <header className="App-header">
        <button onClick={handleSubmit}>Click me!</button>
        {divCreator(count)}
      </header>
    </div>
  );
}

export default App;

Application View

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you mate ! does it work that each div will have different color ?
It's also possible to set different font colour to div content. So you have to manage that inside the loop. You can manage it similar to the way I'm setting key prop inside the div, if you want to set a different colour to each div.
yess it worked. I used random rgb inside the function divCreator. But can you help me on something. I am trying to delete any of the div by clicking on it. Can you help me with it ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.