On submits doesn't trigger a function in ReactJs

39 Views Asked by At
const CreateMessage = () => {
    const disatch = useDispatch()
    const chatR = useSelector(state => state.chat);
    const { chat } = chatR;
    const [text, setText] = useState("")
    useEffect(()=>{
        setText("")
    },[chat])
    
    function handleSubmit(event) {
        event.preventDefault()
        console.log(3333)
      }
    
  return (
    <StyledCreateMessage id="myform" onSubmit={handleSubmit}>
        <div className="searchForm">
            {/* <input className='input' type="text" placeholder='Write a message...' /> */}
            <textarea value={text} onChange={(e)=>setText(e.target.value)}  spellCheck="false" className='input' placeholder='write a message...'></textarea>
        </div>
        <div className="send">
        <Stack direction="row" spacing={1}>
                <IconButton  color="primary" sx={{color:"white"}} aria-label="upload picture" component="label">
                    <input hidden  type="file"  />
                    <AttachFileIcon />
                </IconButton>
                <IconButton  color="primary" sx={{color:"white"}} aria-label="upload picture" component="label">
                    <input hidden type="file" accept='image/*' />
                    <PhotoCamera />
                </IconButton>
                <IconButton type="submit" form="myform" color="primary" sx={{color:"white"}} aria-label="upload picture" component="label">
                    <SendIcon />
                </IconButton>
        </Stack>

        </div>
    </StyledCreateMessage>
  )
}

why when I clock

<IconButton type="submit" form="myform" color="primary" sx={{color:"white"}} aria-label="upload picture" component="label">
   <SendIcon />
</IconButton>

It doesn't trigger handleSubmit

2

There are 2 best solutions below

2
terpinmd On

You need to add onClick={handleSubmit} to your IconButton.

Here is an example right from react docs: https://reactjs.org/docs/forms.html

0
Queens Coder On

Your form won't have the context of the button based on the way you have it set up.

There are a few things you can do

  1. The button would have to be in the form itself, which seems like what you'd want.
  2. Do the onClick solution mentioned above
  3. Pass some state between the form component and the button, which seems difficult for something simple.