Home > Software design >  Handling form with single state in React for web app
Handling form with single state in React for web app

Time:01-01

I have an idea to create simple web app for my own needs. I would like user to be able to use picklist to define number of form fields needed (ex. 1 - 10). Picklist would create chosen number of components with text inputs. User can type string into text input and all data would be stored as single state. I could do it just simply saying string1, string2 and having 10 states but I wonder if this would be doable as single state because I would like all text inputs to create single string in form of token.

Example: User choose 3 text inputs:

  1. hi
  2. hello
  3. goodbye

This would form token of {hi/hello/goodbye}.

Please let me know how to handle that with React.

Thanks.

CodePudding user response:

Probably you can solve this using an array of objects inside your state and latter assessing to the values. I'm not sure what do you want to do, but if you want to create an app that generates dynamically inputs and after set the values in the corresponding state, you can do something like this.


export default function DinamicLinks() {
  const [quantity, setQuantity] = useState(0)
  const [messages, setMessages] = useState([])

  const createInputs = (quantity) => {
    const params = []

    for (let i = 1; i <= quantity; i  ){
      let param = {name:i};
      params.push(param)
    }

    return params
  }

  const handleMessages = (passedMessage) => {
    const filteredMessages = messages.filter((message) => message.name !== passedMessage.name)
    setMessages([...filteredMessages, passedMessage])
  }

  return (
    <div className="App">
       <button onClick={() => setQuantity(quantity   1)}>More inputs</button>
       <button onClick={() => setQuantity(quantity - 1)}>Less inputs</button>
       {createInputs(quantity).map(({name}) => <input key={name} onChange={(e) => handleMessages({name, message:e.currentTarget.value})}></input>)}
       <button onClick={() => console.log(messages)}>See messages</button>
    </div>
  );
} 

This code will go to generate inputs dynamically and will go to store his values inside an state, that store objects inside an array, later you can implement the logic to handle the text in the way you whatever you want. By the way, this code isn't the best in performance, but I want to give you and easy solution quickly. Undoubtedly there are better ways to do this, and also is valid to mention, don't abuse the arrow functions like I did in this example, are an easy ways to have trouble of performance in React.

  • Related