Khaldoun Baz
Khaldoun Baz

Reputation: 21

React function component Callback give not a function error

What is wrong with this function

  function Test({ setColor }) {
   return (
    <div>
     <h1>Test</h1>
     <button onClick={(e) => setColor('black')}>Set Color</button>
     </div>
     );
  }

 export default Test;

to give me this error

Test.js:18 Uncaught TypeError: setColor is not a function at onClick (Test.js:18:1) at HTMLUnknownElement.callCallback

Error

Upvotes: 1

Views: 562

Answers (1)

Nikita Prus
Nikita Prus

Reputation: 351

This error happens because you don't provide any props to your Test component. So, your setColor is undefined and when you want to call setColor you receive an error.

There you have two possible solutions:

  1. Provide default value for setColor prop:
function Test({ setColor = () => {} }) {
  return (
    <div>
      <h1>Test</h1>
      <button onClick={(e) => setColor("black")}>Set Color</button>
    </div>
  );
}
  1. Provide a prop for your component:
export default function App() {
  const [color, setColor] = useState("");

  return (
    <div className="App">
      <Test setColor={setColor} />
      <p>Your color is: {color}</p>
    </div>
  );
}

See this sandbox for more details

Upvotes: 2

Related Questions