Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick event for enter Button in react js

Below code is working fine with button that is created in this code .but i also want to use the enter button to do same work .

<div className="input" >
      <input
        type="text"
        placeholder="Type something..."
        id="myinput"
        onChange={(e) => setText(e.target.value)}
        value={text}
        
      />
      <div className="send">
        {/* <img src={Attach} alt="attach" /> */}
        <input
          type="file"
          style={{ display: "none" }}
          id="file"
          onChange={(e) => setImg(e.target.files[0])}
          />
        <label htmlFor="file">
          <img src={Attach} alt="img" />
        </label>
        <button onClick={handleSend}>Send</button>
    
      </div>

    </div> 

how to achieve that?


2 Answers

Simply you can wrap the input with the form tag and you can use the onSubmit function, In that case, onClick and press enter both will work.

const handleOnSubmit = () => {
  // write your function here

}

<form onSubmit={handleOnSubmit} className="input">
  <input
    type="text"
    placeholder="Type something..."
    id="myinput"
    onChange={(e) => setText(e.target.value)}
    value={text}
  />
  <div className="send">
    {/* <img src={Attach} alt="attach" /> */}
    <input
      type="file"
      style={{ display: 'none' }}
      id="file"
      onChange={(e) => setImg(e.target.files[0])}
    />
    <label htmlFor="file">
      <img src={Attach} alt="img" />
    </label>
    <button type="submit">Send</button>
  </div>
</form>
like image 78
Sabbir Zzaman Avatar answered Mar 14 '26 23:03

Sabbir Zzaman


Basically, there can be many ways to do so, you can use onKeyPress attribute to check if the pressed key is "Enter" and then run the same "handleSend" function.

<button
     onClick={handleSend}
     onKeyDown={e => e.key === 'Enter' ? handleSend: 
''}>Send</button>

this query is already discussed in this thread. Here's a link!

like image 32
Rahul Kumar Avatar answered Mar 14 '26 22:03

Rahul Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!