Search code examples
reactjstypescriptreact-hookstsx

onClick not assignable to type 'IntrinsicAttributes' error in TypeScript React


I have this code for a component:

Feedback.tsx

import React, { useState } from 'react';
import './Feedback.css';

import FeedbackButton from './FeedbackButton';

function Feedback() {
  const [isOpen, setIsOpen] = useState<boolean>(false)

  return (
    <div className="Feedback">
      <FeedbackButton onClick={() => setIsOpen(!isOpen)} />
    </div>
  );
}

export default Feedback;

The FeedbackButton component looks like this:

FeedbackButton.tsx

import React from 'react';
import feedbackicon from './feedback.svg';
import './Feedback.css';

function FeedbackButton() {
  return (
    <button className="Feedback-button" type="button">
      <img src={feedbackicon} className="Feedback-button-icon" alt="feedback" />
    </button>
  );
}

export default FeedbackButton;

On the line <FeedbackButton onClick={() => setIsOpen(!isOpen)} /> I get the error Type '{ onClick: () => void; }' is not assignable to type 'IntrinsicAttributes'. Property 'onClick' does not exist on type 'IntrinsicAttributes'.

I searched it up and tried to fix it using FunctionalComponent, but I got the same error. How can I make this onClick with useState work?


Solution

  • function FeedbackButton(props:{onClick:()=>void}) {
      return (
        <button className="Feedback-button" type="button" onClick={props.onClick}>
          <img src={feedbackicon} className="Feedback-button-icon" alt="feedback" />
        </button>
      );
    }
    

    something like this should work for you even better you can copy the type from button onclick to your props and have better typing if needed