DEV Community

Nikhil Chandra Roy
Nikhil Chandra Roy

Posted on

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.

Top comments (0)