Home > OS >  How to set a default value in an input tag?
How to set a default value in an input tag?

Time:11-06

const [userInfo, setUserInfo] = useState([]);

const handleUserInfo = (id) => {
        fetch(`https://602e7c2c4410730017c50b9d.mockapi.io/users/${id}`)
            .then(res => res.json())
            .then(data => setUserInfo(data)) 
}
<input type="text" defaultValue={userInfo?.profile?.firstName   userInfo?.profile?.lastName} className="form-control bg-light" id="exampleInputName" aria-describedby="name"></input>

I am expecting to see both firstname and last name in that input field with a gap between first name and last name. But I see NAN because I tried to add firstname and lastname using plus ( ) The NAN doesn't show up if I only want to see the first name when the default value is defaultValue={userInfo?.profile?.firstName}

CodePudding user response:

You have a typo when you are trying to display default value, try to change userInfo?.profile?.firstName userInfo?.profile?.lastlName to userInfo?.profile?.firstName userInfo?.profile?.lastName. (lastName was misspelled incorrectly). also it's a better way to use template literals

CodePudding user response:

Hello and welcome to Stack Overflow!

Input's defaultValue is set on the initial load of your component. Your request is asynchronous which means that you are probably getting the result after the initial load. So you need to transform your component into a controlled component. Meaning, you will have to create a state that will hold the input value as well as to listen on the onChange event and alter your state to reflect the changes. You can check the official docs here for more info on forms and their behavior.

export default function ExampleComponent() {
  const [userInfo, setUserInfo] = React.useState([]);
  const [inputValue, setInputValue] = React.useState('');

  React.useEffect( () => {
    handleUserInfo(5)
  }, [])

  const handleUserInfo = (id) => {
    fetch(`https://602e7c2c4410730017c50b9d.mockapi.io/users/${id}`)
        .then(res => res.json())
        .then(data => {
          setInputValue(`${data?.profile?.firstName} ${data?.profile?.lastName}`)
          setUserInfo(data)
        } )
  }
  
  return (
    <input 
      type="text"
      value={inputValue}
      onChange={(e) => setInputValue(e.target.value)}
      className="form-control bg-light" 
      id="exampleInputName" 
      aria-describedby="name"
    />
  )
}
  • Related