Search code examples
reactjscontrolled-component

React Input type not able to insert any data


In my React component I have used input type; but somehow it is not going to to editable anyhow.

I have checked this post as well but not able to trace the solution.

const Index = ({
  const [editable, setEditable] = useState(false)
  const [email, setEmail] = useState('')

  useEffect(() => {
    if (data) {
      setEmail(data.primaryEmail)
    }
  }, [data])

  return (
    <Emails 
      data={data} 
      changeHandle={e => setEmail(e.target.value)}
      emailName={email}
    />
  )
})

export default connect(mapStateToProps)(Index)


const Emails = ({
    data,
    changeHandle,
    emailName
  }) => {

return (
  <Card>
    <React.Fragment>
      <tr key={email}>
        <td className="text-gray-6 pl-0 pb-0">
          <input className="mb-2" value={emailName} onChange={e => changeHandle(e)} />
        </td>
      </tr>
    </React.Fragment>
  </Card>
)
}

export default Emails

What's am I doing in this above code ?


Solution

  • You're passing the email as a prop, but in your Emails element, it just takes 'data' and 'channgeHandle'. Try to add email as a prop:

    const Emails = ({ data, email, changeHandle }) => {
      return (
        <Card>
            <tr key={email}>
              <td className="text-gray-6 pl-0 pb-0">
                <input className="mb-2" value={email} onChange={e => changeHandle(e)} />
              </td>
            </tr>
        </Card>
      )
    }
    

    After that, pass the setEmail to the changeHandle prop:

    return (
        <Emails 
          data={data} 
          changeHandle={e => setEmail(e.target.value)}
          emailName={email}
        />
      )
    

    Beside this, apparently your data prop is not used at any moment, so I don't see the utility for it.