DEV Community

Nikhil Chandra Roy
Nikhil Chandra Roy

Posted on

1

How to use ReactJs setState to repeat the list of html (Short Tutorial)

Hi, Namaste.

After spending hours of time with reactjs I got the code to fix my reactjs issue, It's very shy for me because I used this react way many times but still hesitate to use it the proper way.

Here is return code look like

return (
        <div>
          <input type="text" onKeyDown={downHandler}/>
          <ul>
              {list.map(v=> <li key={keyId++}>{v}</li> )}
          </ul>
        </div>
    )

Enter fullscreen mode Exit fullscreen mode

and inside function I have used to repeat the html list so it's repeating the ul li tag with the input value.
for the unique key I have used one variable called "keyId" and I put it inside key attribute to make it unique.

const [list, setList] = useState([]);
    let keyId = 1;
    const downHandler = e=> {
        if(e.key === 'Enter'){
            setList(old=> [...old, e.target.value])
        }
    }

Enter fullscreen mode Exit fullscreen mode

That's taking me hours of time to finding it on the internet.
Though it is very shy reactjs made my day messy and founding each issue to build something.

Below the full code to repeat ul li tag with input value whenever hit 'Enter'

import React, {useState} from 'react'

function February_4() {
    const [list, setList] = useState([]);
    let keyId = 1;
    const downHandler = e=> {
        if(e.key === 'Enter'){
            setList(old=> [...old, e.target.value])
        }
    }
    return (
        <div>
          <input type="text" onKeyDown={downHandler}/>
          <ul>
              {list.map(v=> <li key={keyId++}>{v}</li> )}
          </ul>
        </div>
    )
}

export default February_4


Enter fullscreen mode Exit fullscreen mode

To get more content like this and to be shy with reactjs dummy issue stay with me.
Thanks.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more