Search code examples
reactjscomponentsjsxreact-props

How do I solve an error in my React Button Component?


I have an error in my Button component but I don't know what is wrong. It would be great if somebody can help me... The code is below. Recently I added ESLint + Prettier but I don't know if that's the problem.

■Exported file

import React from 'react';
import classes from './Button.module.css';

const Button = (props) => {
return (
<button
  type={props.type}
  className={`${classes.button} ${props.className}`}
  onClick={props.onClick}
>
  {props.children}
</button>
  );
};

export default Button;

■Imported file

import Button from '../UI/Button';

const Login = () => {
return (
<div>
  <form>
    <Button
      type='submit'
      className={classes['login-btn']}
      onClick={submitLoginHandler}
    >
      Login
    </Button>
  </form>
</div>
);
};

export default Login;

■Error enter image description here


Solution

  • Those are warning not error. Its say you must check your prop type (String,İnt,Bool,Func)

    For your code:

    Button.propTypes = {
      type: PropTypes.string,
      className:PropTypes.string,
      onClick: PropTypes.func,
      children: PropTypes.string
    };
    

    But I recommend you to not use children prop use for example use buttonLabel.

    <Button
      type='submit'
      className={classes['login-btn']}
      onClick={submitLoginHandler}
      buttonLabel="Login"
      />
    

    And get props like this :

    const Button = ({type,className,onClick,buttonLabel}) => {
    return (
    <button
      type={type}
      className={`${classes.button} ${className}`}
      onClick={onClick}
    >
      {buttonLabel}
    </button>
      );
    };
    

    Final Proptypes:

    Button.propTypes = {
      type: PropTypes.string,
      className:PropTypes.string,
      onClick: PropTypes.func,
      buttonLabel: PropTypes.string
    };
    

    More info : https://reactjs.org/docs/typechecking-with-proptypes.htm