-1

I am trying to apply the following form for submission in React, but nothing is being shown in the input text field that I type. Hence the onClick does not get fired as well.

I saw a lot of posts but I could not find the solution to my issue, I'm a beginner as well.

    <form>
          <input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            type="text"
            placeholder="Type a message"
          />
          <button onClick={sendMessage} type="submit">
            Send
          </button>
          {/* onClick={sendMessage} */}
        </form>

And the sendMessage is defined as below:

function Chat({ messages }) {
  const [input, setInput] = useState("");

  const sendMessage = async (e) => {
    e.preventDefault();
    await axios.post("/messages/new", {
      message: input,
      name: "Abhi",
      received: true,
      timestamp: "Just Now",
    });

    setInput("");
  };
// below contains the render return () which consists the form shown above.
Abhiram Satputé
  • 604
  • 1
  • 5
  • 21

1 Answers1

0
  1. Form elements don't require form. As long as your form elements are contained it's perfectly valid HTML. Which means you can use a div and remove the e.preventDefault() from your handler.

  2. You can then remove the type=submit attribute from your button as it's no longer needed. Just use the onClick handler.

  3. Perhaps use a separate handler for the input for clarity.

  4. sendMessage probably doesn't need to be async as you're not returning anything from your Axios process that the state function relies on for its update, so make it a standard function instead.

const { useState } = React;

function Chat() {

  const [ input, setInput ] = useState('');

  function handleChange(e) {
    const { value } = e.target;
    console.log(value);
    setInput(value);
  }

  function sendMessage() {
    console.log(`Final state: ${input}`);
    // AXIOS here
    setInput('');
  }

  return (
    <div>
      <input
        value={input}
        onChange={handleChange}
        type="text"
        placeholder="Type a message"
      />
      <button onClick={sendMessage}>Send</button>
    </div>
  );
};

// Render it
ReactDOM.render(
  <Chat />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Andy
  • 61,948
  • 13
  • 68
  • 95