Home > database >  How can I create a new line when hit enter in an input field?
How can I create a new line when hit enter in an input field?

Time:03-11

I need to create a newline when enter is hit and submit the form only when clicked on button.

<form className="message_form" onSubmit={handleSubmit} >
     
      <div>
        <input
          type="text"
          placeholder="Enter message"
          value={text}
          onChange={(e) => setText(e.target.value)}
        />
      </div>
      <div>
        <button className="btn">Send</button>
      </div>
    </form>

CodePudding user response:

To make the foem submit on a button click, you need to remove the onSubmit from tag and then make your button type="submit" . this will submit the form iff button is clicked. And for enter you need to capture the key press event ( assuming you are talking about enter while typing in the input field ) as ( this code will go in your onChangeHandler for input field:

if (e.key === 'Enter') {
      setMakeTheLineVisible(true)
 } 

After getting the enter key you can toggle the state which will make the line you want visible on the page.

CodePudding user response:

You can use a textarea instead of an input box and add the click event on the Send button. It'll look something like this:

import React, { useState } from "react";
import './App.css'
const App = () => {
  const [text, setText] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("text", text);
  };

  return (
    <form className="message_form">
      <div>
        <textarea
          type="text"
          placeholder="Enter message"
          rows={4}
          value={text}
          onChange={(e) => {
            setText(e.target.value);
          }}
        >
          {text}
        </textarea>
      </div>
      <div>
        <button className="btn" onClick={handleSubmit}>
          Send
        </button>
      </div>
    </form>
  );
};

export default App;

You can check here for more info, it's a similar kind of question. Might help you further - Similar question on SO

  • Related