2

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?

1
  • a click handler on a button element should automatically be fired when the user presses Enter (or Space) when the button is focused. Do you want it to fire when the user presses enter anywhere on the page? In that case you need to add an event listener to the document (in a useEffect, and remove it in the cleanup). Commented Dec 31, 2022 at 12:26

2 Answers 2

5

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Upvoted for sensible use of the standard web API. Too much React code deviates from this...
4

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!

3 Comments

as I already pointed out in a comment, this is absolutely not necessary. If this isn't working for the OP they should edit their question to give more detail.
Thank you bhai but its not working will you please resend this
I think the reason this isn't working is because the function handleSend needs to be called. e => e.key === 'Enter' ? handleSend() : null