I'm recently migrate to Typescript-react from javascript-based react. So this is new for me.
I notice that Typescript has its own props validation method using interface
. My questions are:
- Does PropTypes (from prop-types package) still necessary to be used ?
- How to make "isRequired" for a prop? I want to make it error if a prop doesn't defined.
- How to make a default value for a prop? I want to use that default value if a prop wasn't defined.
Here is my simple code. This code below works:
import * as React from "react";
// [Question 1] Create an object PropTypes, is this still necessary ?
import * as PropTypes from "prop-types";
// [Question 2] how to use isRequired for this prop ?
interface Props {
text: String;
active: Boolean;
}
const NavBarMenu = (props: Props) => {
// [Question 3] How to make a default value for prop?
return (
<li className="nav-item">
<a className={props.active ? "nav-link active" : "nav-link"} data-toggle="tab" href="#" role="tab">
{props.text}
</a>
</li>
);
};
NavBarMenu.propTypes = {
text: PropTypes.string.isRequired,
active: PropTypes.bool
};
export default NavBarMenu;