0

I have two fields and a button. I want to render input values on the click of a button. Can you guys please tell me how to do it?

function Home() {
  const [name, setName] = useState('')
  const [age, setAge] = useState(0)

  const submitForm = () => {
    console.log(name, age)
  }

  return (
    <div>
      <div>
        <label htmlFor="name">Name:</label>
        <input type="text" value={name} onChange={e => setName(e.target.value)} />
      </div>
      <div>
        <label htmlFor="age">age:</label>
        <input type="number" value={age} onChange={e => setAge(e.target.value)} />
      </div>
      <button onClick={submitForm}>Submit</button>
      <h1>render "name" gere</h1>
      <h2>render "age" gere</h>
    </div>
  )
}

export default Home

3 Answers 3

2

You can add a state to track the display state, as

  const [visible, setVisible] = useState(false)

Alter it in form submit as:

const submitForm = () => {
    setVisible(true)
  }

And render it as:

{visible && <><h1>render {name} gere</h1>
             <h2>render {age} gere</h2> </>}
Sign up to request clarification or add additional context in comments.

Comments

0

I fix it like this.

function Home() {
  const [name, setName] = useState('')
  const [age, setAge] = useState(0)
  const [data, setData] = useState({})

  const submitForm = () => {
    setData({name, age})
  }

  return (
    <div>
      <div>
        <label htmlFor="name">Name:</label>
        <input type="text" value={name} onChange={e => setName(e.target.value)} />
      </div>
      <div>
        <label htmlFor="age">age:</label>
        <input type="number" value={age} onChange={e => setAge(e.target.value)} />
      </div>
      <button onClick={submitForm}>Submit</button>
      <h1>{data.name}</h1>
      <h2>{data.age}</h2>
    </div>
  )
}

export default Home

1 Comment

Data will be visible before submission. And you need not return data in submitForm
0

Try this and see if it helps.

 function Home() {
  const {register, handleSubmit} = useForm()

  const onSubmit = (data) => {
    console.log(data)
  }
  
 return (
 <form onSubmit = {handleSubmit(onSubmit)}>
    <div>
      <div>
        <label htmlFor="name">Name:</label>
        <input type="text" value={name} onChange={e => setName(e.target.value)} />
      </div>
      <div>
        <label htmlFor="age">age:</label>
        <input type="number" value={age} onChange={e => setAge(e.target.value)} />
      </div>
      <button onSubmit={submitForm}>Submit</button>
      <h1>render "name" gere</h1>
      <h2>render "age" gere</h>
    </div>
    <form/>
  );
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.