Button Ubmit and building components dynamically in Reactjs

Asked

Viewed 168 times

-1

I’m making a revenue registration page. This is my form:

<form onSubmit={handleSubmit}>
      <Input 
        name="title"
        label="Nome da receita:"
        type="text"
        value={title}
        onChange={(event) => { setTitle(event.target.value)}}
      />
      
      <div>
        <table>
          <thead>
            <tr>
              <th>Ingrediente</th>
              <th>Quantidade</th>
            </tr>
          </thead>
        </table>
      </div>

      <div >
        <Input 
          
          name="ingredient"
          label=""
          type="text"
          value={ingredient}
          onChange={(event) => { setIngredient(event.target.value)}}
        />
        <Input 
          
          name="quant"
          label=""
          type="text"
          value={quant}
          onChange={(event) => { setQuant(event.target.value)}}
        />
      </div>
        <button onClick={handleIngredient}>
          Incluir ingrediente
        </button>
        
      <TextArea 
        name='direction'
        label='Modo de fazer:'
        type="text"
        value={direction}
        onChange={(event) => { setDirection(event.target.value)}}
      />
      <div>
        <button type="submit">
          Cadastrar receita
        </button>
      </div>
    </form>

When the user clicks on the Include ingredient button, I would like the page to show two more inputs, one for the ingredient and one for the quantity. So far I have created the following. (This snippet is called in the handleIngredient function):

function handleIngredient( ){
     <>
      <div>
        <Input 
          name="ingredient"
          label=""
          type="text"
          value={ingredient}
          onChange={(event) => { setIngredient(event.target.value)}}
        />
        <Input 
          name="quant"
          label=""
          type="text"
          value={quant}
          onChange={(event) => { setQuant(event.target.value)}}
        />
      </div>
        <button onClick={handleIngredient}>
          Incluir ingrediente
        </button> 
    </>     

}

But it does not return the inputs, and the worst: it returns the content of handleSubmit. So I have these two questions: How do I create these two inputs from the click of the button; Why this button (which is not Submit) calls the Submit function.

Thank you all.

1 answer

1


Usually when you start with React this is one of the difficulties to understand the state(s) of a component and when you want to create elements that may have a list in your case are ingredients of a recipe your component needs to have a list of ingredients so that clicking on a button has the effect of adding new ingredients to that recipe, a basic example:

function App() {
  const valueBase = {description: '', quantidade: 0};
  const [ingredientes, setIngredientes] = 
    React.useState([{...valueBase}]);
  const handleAdd = () => {
    setIngredientes(state => [...state, {... valueBase}]);
  }
  const handleChange = (e, ix) => {
    const {name, value} = e.target;
    let values = [...ingredientes];
    values[ix][name] = value;
    setIngredientes(state => [...values]);
  }
  const handleDelete = (ix) => {
    let values = ingredientes.filter((a, b) => {    
      if (b !== ix) {
        return a;
      }
    });
    setIngredientes(state => [...values]);    
  }
  return (
    <div>
      <div>
        {ingredientes.map((ing, ix) => (
          <div>
            <label> Descrição:
            <input name="description" type="text" value={ing.description} onChange={e => handleChange(e, ix)} style={{width: 100}} />
            </label>
            <label> Quantidade:
            <input name="quantidade" type="number" value={ing.quantidade} onChange={e => handleChange(e, ix)} style={{width:50}}/>
            </label> { ' ' }
            <button onClick={e => handleDelete(ix)}>Remover</button>
          </div>
        ))}
        <br />
        <br />
        <button onClick={handleAdd}>Adicionar Ingrediente</button>
        <pre>
          {JSON.stringify(ingredientes, null, 2)}
        </pre>
      </div>
    </div>
  )
}

ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

When you want to duplicate items in the component, always create a array, example

const [values, setValues] = React.useState([]); // [] significa lista, array

and in each position an object ({}) with the keys you so need. I also made in this example the exclusion of some ingredient that was added erroneously.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.