Search code examples
reactjsreact-hookslivechat

Clear input field using React hooks


I'm building a live chat-app and having trouble with clearing the input field. After form is submitted, I want the input field to be cleared. I changed the state to an empty sdtate but not working at all.

import React, { useState, useEffect, useContext } from 'react'
import io from 'socket.io-client'
import './ChatRoom.css'
import { ChatContext } from '../ChatContext'
import ScrollToBottom from 'react-scroll-to-bottom'


const ChatRoom = () => {
    const { userName, setUserName } = useContext(ChatContext)
    const { roomCode, setRoomCode } = useContext(ChatContext)
    const [message, setMessage] = useState('')
    const [chats, setChats] = useState([])

    const handleMessage = (e) => {
        var newMessage = e.currentTarget.value
        // console.log(newMessage)
        setMessage(newMessage)
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        console.log('Message submitted')
        setMessage("")
    }

    return (
        <>
            <div className="top-container">
                <h2>123</h2>
            </div>
            <div className="chat-container">
            {/* {renderChat()} */}
            <h1>hello</h1>
            </div>
            <form className="form-inline" onSubmit={handleSubmit}>
                <input type="text" onChange={handleMessage} className="form-control mb-2 mr-sm-2" id="inlineFormInputName2" placeholder="Type your message here..."/>
                <button type="submit" className="btn btn-primary mb-2">Send</button>
            </form>
        </>
        
    )
}


export default ChatRoom;

Solution

  • You’re using an uncontrolled input. Try setting value={message} on the input.