Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding proptypes to unnamed anonymous default exported functions - e.i "export default () =>{}"

I know you can do the following:

import React from "react";
import PropTypes from "prop-types";

const Header = ({ name }) => <div>hi {name}</div>;

Header.propTypes = {
  name: PropTypes.string
};

export default Header

However can I assign propTypes with anonymously exported default functions (export default () =>{}) like the following?:

 export default ({ name }) => <div>hi {name}</div>;


 //how do I do this part/ is it possible?
   ?.propTypes = {
      name: PropTypes.string
   };

EDIT: I tried:

    export default ({ name }) => (<div>
//  ----- here ------- (makes sense why, it doesn't work) 
    static propTypes = {
      name: PropTypes.string
    }
// ---------------
     {name}
    </div>);

and:

// -------and like this at bottom --------
    default.propTypes = {
      name: PropTypes.string
    }
// ------------------

I don't think it is possible, exporting this way, just one of the tried offs on the overall approached.

like image 488
garrettmac Avatar asked Jul 10 '18 18:07

garrettmac


People also ask

What does the PropTypes check do for the component?

What are PropTypes? PropTypes are simply a mechanism that ensures that the passed value is of the correct datatype. This makes sure that we don't receive an error at the very end of our app by the console which might not be easy to deal with.

Is PropTypes deprecated?

5 PropTypes are deprecated in the React package and have been given a package of their own. Change is an inevitable part of life. The upshot is twofold. 1) If you use another type-checking mechanism, you don't have to worry about shipping unnecessary bulk to your end users.

What is the purpose of the PropTypes package?

If you prefer to exclude prop-types from your application and use it globally via window. PropTypes , the prop-types package provides single-file distributions, which are hosted on the following CDNs: unpkg.

What is PropTypes node?

PropTypes. node: any render-able value like numbers and string, that can actually be rendered on screen. PropTypes. any: any type of value, even those are non-render-able like boolean.


1 Answers

The sane way to do this is to just assign the function to a variable:

const anon = ({ name }) => <div>hi {name}</div>;
anon.propTypes = {
  name: PropTypes.string
};

export default anon; 

If you truly believe you have a reason not to do it the sane way, how about Object.assign?

export default Object.assign(
  ({ name }) => <div>hi {name}</div>,
  { propTypes: { name: PropTypes.string } }
);
like image 73
Jordan Running Avatar answered Nov 01 '22 18:11

Jordan Running