React hooks: Invalid hook call

Viewed 288

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>
  );
}
2 Answers

You have to declare like this

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

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>
  );
}
Related