Home > Blockchain >  is there any way to make sure that I am passing a component with certain props
is there any way to make sure that I am passing a component with certain props

Time:11-01

If I have a component that will have a prop value or children as other JSX functional components and I want to make sure that those components have certain props passed enter image description here

so here I want to make sure if another developer used the component the inputs will have like <Trail value=''/>

CodePudding user response:

You can use PropTypes for that. PropTypes is a library that let you specify what props your component will receive and if the props are required or not.

In your case, an example of PropTypes implementation would be:

import PropTypes from "prop-types";

export default function Trail(props) {
  return <span>{props.value}</span>;
}

Trail.propTypes = {
  value: PropTypes.string.isRequired
};

And If value is not passed as props to your component, it would trigger a warning in the console.

Find more info about usage and Types at the official React documentation on the topic and on the package page.

CodePudding user response:

Since you have tagged this question with TypeScript, I will answer accordingly.

You can define your props type. Then the TypeScript compiler will complain if the required props are not supplied.

type Props = {
    value: string;
};

const Trail = ({ value }: Props) => {
    // Implementation
}

Alternatively you can use interface instead of type.

See this cheetsheet for more info: https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/basic_type_example.

  • Related