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.
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.
Share Improve this question edited Jul 10, 2018 at 18:41 garrettmac asked Jul 10, 2018 at 18:32 garrettmacgarrettmac 8,5853 gold badges43 silver badges61 bronze badges 2 |2 Answers
Reset to default 21The 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 } }
);
Found out how, I could do the following:
require('./Header').default.propTypes = {
name: PropTypes.string
};
Where Header
is the file exported.
Any disadvantages to this approach (is this loading the same file back into memory?)? Don't ever see this pattern in the wild? That probably for a good reason because I'm re-importing it.
static
is only for defining static properties of classes, anddefault
isn't a variable. – Kevin B Commented Jul 10, 2018 at 18:48