2

Trying to create a form to sell and item. Trying to test out printing itemName in a <h1>, but keep getting the following error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

Someone able to shed light on what I'm doing wrong:

import React, { useState } from "react";
import Navbar from "./Navbar";

function Selling() {
  const [itemName, setItemName] = useState("");

  function handleChange(event) {
    setItemName(event.target.value);
  }

  return (
    <div>
      <form>
        <h4 className="selling-input-title">What are you selling?</h4>
        <div class="form-group">
          <input type="text"
            onChange={handleChange}
            class="form-control item"
            id="usr"
            value={itemName} />
        </div>
      </form>
      <h1>{itemName}</h1>
    </div>
  );
}
cpog90
  • 97
  • 6
  • Can you format your code so it's easier to read for us to help? And also remove everything that isn't relevant to the issue / necessary to reproduce the problem. – Sheraff Aug 12 '20 at 17:40
  • 1
    Your component `Selling` is correct. Your error is likely coming from another part of your code. You may need to share other parts to identify the problem root. – buzatto Jan 16 '21 at 17:08
  • Does this answer your question? [Invalid hook call. Hooks can only be called inside of the body of a function component](https://stackoverflow.com/questions/56663785/invalid-hook-call-hooks-can-only-be-called-inside-of-the-body-of-a-function-com) – amirhe Jan 17 '21 at 03:06

2 Answers2

0

You have to declare like this

  const handleChange = (event) => {
  setItemName(event.target.value);
  }
Jay Parmar
  • 368
  • 2
  • 9
0

Try this:

import React, { useState } from "react";
import Navbar from "./Navbar";

export default () => {
  const [itemName, setItemName] = useState("");

  const handleChange = (event) => {
  setItemName(event.target.value);
  }

  return (
    <div>
      <form>
        <h4 className="selling-input-title">What are you selling?</h4>
        <div class="form-group">
          <input type="text"
            onChange={handleChange}
            class="form-control item"
            id="usr"
            value={itemName} />
        </div>
      </form>
      <h1>{itemName}</h1>
    </div>
  );
}
Sakshi
  • 1,464
  • 2
  • 8
  • 15