I create app that render inputs dynamically, some result of calculations I need to set to every block to spans className="strongCrist" and className="strongRuby". But sets only same value to all blocks spans. On pure JavaScript it was very simple - in loop we add innerHTML to span and add span by parentElement.appendChild.
const { useState, useEffect } = React;
function PrimaryInputs() {
const [playersQuantity, setPlayersQuantity] = useState(0);
const [cristQuantity, setCristQuantity] = useState(0);
const [rubyQuantity, setRubyQuantity] = useState(0);
const [isCalculated, setIsCalculated] = useState(false);
const [inputs, setInputs] = useState({});
const [cupsQuantity, setCupsQuantity] = useState(0);
const [dole, setDole] = useState(0);
const [doleCrist, setDoleCrist] = useState(0);
const [doleRuby, setDoleRuby] = useState(0);
function playersHandleChange(event) {
setPlayersQuantity(event.target.value);
}
function cristHandleChange(event) {
setCristQuantity(event.target.value);
}
function rubyHandleChange(event) {
setRubyQuantity(event.target.value);
}
function iterator(quantity) {
let elems = [];
for (var i = 0; i < quantity; i++) {
elems.push(
<div
className={`playersBlock ${isCalculated ? "calculated" : ""} `}
key={`player${i}`}
>
<input
type="number"
name={`cupsOf${i}`}
placeholder="players cups"
className="plCup"
onChange={cupsHandleChange}
/>
<br />
<span className="strongCrist">Cristalls: {doleCrist}</span>
<br />
<span className="strongRuby">Rubies: {doleRuby}</span>
</div>
);
}
return elems;
}
function cupsHandleChange(event) {
const { name, value } = event.target;
setInputs((prev) => {
return { ...prev, [name]: Number(value) };
});
setIsCalculated(true);
}
function countCups() {
let i = 0;
for (const key in inputs) {
const val = inputs[key];
if (val) {
i += val;
}
setCupsQuantity(i);
}
}
function countDole() {
for (const key in inputs) {
const val = inputs[key];
if (val) {
setDole(val / cupsQuantity);
setDoleCrist(Math.round(dole * cristQuantity));
setDoleRuby(Math.round(dole * rubyQuantity));
}
}
}
useEffect(() => {
countCups();
countDole();
});
return (
<>
<div className="mainInputs">
<div className="input_wrapper">
<label htmlFor="players">Enter quantity of players</label>
<input
type="number"
name="players"
id="players"
onChange={playersHandleChange}
/>
</div>
<div className="input_wrapper">
<label htmlFor="cristall">Enter cristalls</label>
<input
type="number"
name="cristall"
id="allCrist"
onChange={cristHandleChange}
/>
</div>
<div className="input_wrapper">
<label htmlFor="ruby">Enter rubies</label>
<input
type="number"
name="ruby"
id="allRuby"
onChange={rubyHandleChange}
/>
</div>
</div>
<hr />
<span>
{playersQuantity ? `players quantity: ${playersQuantity}` : null}
</span>
<br />
<span className="sumCup">
{cupsQuantity ? `cups quantity: ${cupsQuantity}` : null}
</span>
<div id="playersList">{iterator(playersQuantity)}</div>
</>
);
}
ReactDOM.render(
<>
<PrimaryInputs />
</>,
document.getElementById("mydiv")
);