0

I have some difficulties with a little peace of React code that I am writing.

The Goal:
You select, for example, the number 4 from a selection field. Which will result in having 4 (the same amount as the selected number) input fields appear below.

The Problem:
I can't seem to make the equal amount of inputs appear in my DOM.
image:
wrong_result

My Code:

calc.js
    useEffect(() => {
        setLevelInputs([LevelInputs, {id: 0}]);
        for (let i = 0; i < BarracksLevel.length; i++) {
            const number = i
            
            setLevelInputs(...LevelInputs, {id: number});
        }
        setDisplayBoxes(
            <>
                { LevelInputs.map((item, index) => {
                    
                    return (
                        <>
                            <input key={item.id} type="number" onChange={(e) => {setFighterLevels({...FighterLevels, [e.target.value]: e.target.value})}} name={"input_"+item.id} className="TailwindCSS"></input>
                        </>
                    );
                    })}
            </>
        )

    }, [BarracksLevel]);

I might have overlooked something very simple, but thought it wouldn't hurt to ask!

Thanks in advance, An enthusiastic Rookie

Basile
  • 150
  • 11

1 Answers1

0

const { useState, useEffect } = React
const App = () => {
  const [count, setCount] = useState(1);
  const [inputs, setInputs] = useState([<input />])
  useEffect(() => setInputs(
    Array.from({length: count}).map(_ => <input />)
  ), [count])
  return <div><input type="number" value={count} onChange={e => setCount(e.target.value)} />{inputs}</div>  
}
ReactDOM.render(<App/>, app)
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id=app>
bel3atar
  • 913
  • 4
  • 6