#Typescript React and MouseEventHandler Type Error

5 messages · Page 1 of 1 (latest)

split rampart
#

I have an issue trying to find the right Type for my code

The onClick={() => onToggle('input-box')} line in ErrorBox.tsx file is giving me the type error Argument of type 'string' is not assignable to parameter of type 'MouseEvent<HTMLButtonElement, MouseEvent>'. (ts 2345).

Essentially I need to pass a string argument to onToggle('argument-string') so I need to keep that functionality.
MainContent.tsx

import React, { useEffect, useState } from 'react';
import ErrorBox from './ErrorBox';
import InputOptions from './InputOptions';

export default function MainContent() {
  const [showInputOptions, setShowInputOptions] = useState('input-box');

  useEffect(() => {
    // Recieve errorData from Main
    window.textAPI.send_error(errorData => {
      setShowInputOptions('error-box');
      console.log(errorData);
    });
  });

  const handleToggle = box => {
    setShowInputOptions(box);
  };
  return (
    <main>
      <div className="bg-image">
        <div className="overlay">
          <div id="input-section">
            <div id="central-container">
              <InputOptions isVisible={showInputOptions} onToggle={handleToggle} />
              <ErrorBox isVisible={showInputOptions} onToggle={handleToggle} />
            </div>
          </div>
        </div>
      </div>
    </main>
  );
}

ErrorBox.tsx

interface ToggleProps {
  isVisible: string;
  onToggle: React.MouseEventHandler<HTMLButtonElement>;
}

const errorBox: React.FC<ToggleProps> = ({ isVisible, onToggle }) => {
  if (isVisible !== 'error-box') {
    return null;
  }

  return (
    <div id="error-box">
      <div id="error-box-btn">
        <h3>Fix Data Errors:</h3>
        <button
          // TODO: fix type error
          onClick={() => onToggle('input-box')}
          type="button"
          id="close-btn-error"
          className="paste-box-btns fade-in-1s"
        >
          :x:
        </button>
      </div>
    </div>
  );
};

export default errorBox;
mortal skiff
#

if you need to pass a string to onToggle, why did you type it as React.MouseEventHandler<HTMLButtonElement>? it doesn't look like a mouse event handler. i may be missing something though

#

if your question is "how do i write the type for a function which takes a string?", maybe this is what you're looking for:

celest sinewBOT
#
mkantor#0

Preview:ts ... onToggle: (box: string) => void ...

mortal skiff