Home > Back-end >  Reactjs input tag causing the whole page to not load
Reactjs input tag causing the whole page to not load

Time:01-08

So, I was learning React Hooks and everything was going fine until the tag was added as I normally would add it like this: , however, this caused the whole page to collapse but writing it in this way, or react usual way to witting tags made it work again. any explanation behind this?

import React from 'react'
import { useState } from 'react'

function CounterHook() {
    const [count, Setcount] = useState(0)
    let [text, set_text] = useState("This is a Test TEXT")
    let [info , set_info] = useState({name:'', email:''})

    return (
    <div>
        <h3>{count}</h3>
        <button  onClick={() => Setcount(count   1)} className='btn btn-primary'> Click </button>
        <h3> {text} </h3>

        <button  onClick={()=> set_text("The test Text has change nothing is the same anymore ")}  
        className='btn btn-success'> Change Me </button>
        <br />
        <br />
        
        <form>
            <input type="text" className={'form-control'} value={info.name}
         onChange={ event => set_info({name: event.target.value})} /> Enter your Name

        <input type={'text'} className={'form-control'} value={info.email} 
        onChange={ event => set_info({email: event.target.value})} /> Enter your Email
        
        {/* COMMENTED OUT CODE */} {/* that part of the code made the whole page blank */}
        {/* <input type="text" className={'form-control'} value={info.name}
         onChange={ event => set_info({name: event.target.value})}>  Enter your Name </input>

        <input type={'text'} className={'form-control'} value={info.email} 
        onChange={ event => set_info({email: event.target.value})}> Enter your Email </input> */}

        <h2> Name is: {info.name} </h2>
        <h2> Email is : {info.email} </h2>
        </form>
        
    </div>
  )
}

export default CounterHook

CodePudding user response:

So one problem that immediately jumps out at me is that info is supposed to be an object with the shape: {name:'', email:''} but you are setting it to {name:''} or {email:''} which will cause the object to be missing one of the object props. You are then trying to reference both props in which one of them will be undefined depending on what input you type in. Try having two separate states for each of the values like so:

const [name, setName] = useState('');
const [email, setEmail] = useState('');

Alternatively, you could try in your onChange event something like this:

This is for the name input event handler:

previousState => setName(previousState.target.value)

I haven't tested option 2 but in theory, it should work. Hope this helps.

  • Related