1

I have couple of input fields and submit button - each time the values are written to inputs and are submitted only one of the input values will display randomly.

Example:

Example

Instead of outputting all the values I need to print only one - randomly - and each time I will click on the submit another random value from input will appear. For that I guess I need to save somehow the values, so after each submit, the form will not reload empty.

This is how I handle it now:

const [values, setValues] = useState([]);

    const addValue = (input1, input2, input3, input4) => {
        setValues([...values, {input1, input2, input3, input4 }])
    }

    const [input1, setInput1] = useState('');
    const [input2, setInput2] = useState('');
    const [input3, setInput3] = useState('');
    const [input4, setInput4] = useState('');

const handleSubmit = (e) => {
    e.predeventDefault()
    addValue(input1);
    setInput1('');
    addValue(input2);
    setInput2('');
    addValue(input3);
    setInput3('');
    addValue(input4);
    setInput4('');
}

And my view:

{values.map(value => {
            return( <li key={value.input1}></li>)
        })}
            <form onSubmit={handleSubmit}>
            <input type="text" value={input1} onChange={(e) => setInput1(e.target.value )}/>

// the same repeated with input2, input3,....

My question is, how can I handle my solution ? I am new to react and I am not aware of the best ways how to handle it.

  • If you want to pick a random item from an array of itmes you can use `Math.random`. See this [link](https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array). But I'm not really sure of your requirements and what do you want to achieve, so I hope this helps. – c0m1t Jan 29 '21 at 11:12

1 Answers1

0

Simplest solution based on your code would be something like this:

const addValue = (input1, input2, input3, input4) => {
   // You don't have to make an object
   setValues([input1, input2, input3, input4]);
};

const handleSubmit = e => {
    e.preventDefault();
    addValue(input1, input2, input3, input4);
};

// a function to generate random numbers between 0 and 3
const generateRandomNumber = () => {
  return parseInt(Math.random() * 4, 10);
};

And then simply return values array with a random child each time. Like this:

{values[generateRandomNumber()]}

Working code in Codesandbox

Jalal
  • 334
  • 1
  • 4
  • 16