Set a prop's default value as another prop's value? (PropTypes)

719 Views Asked by At

I have a prop driven that takes its value from another prop source. driven can be passed a value itself, breaking that link, but by default it follows it.

Setting a default prop for source is straightforward, but how can I reference source in driven's default prop.

const Example = ({source = 'foo', driven = source}) => <div />

Example.defaultProps = {
  source: 'foo',
  driven: /* ? */
}
2

There are 2 best solutions below

1
Mr. Polywhirl On

If you need driven to be an alias for source, you can use a nullish-coalescing operation inside the component memoization:

/* 
 * Does something. If driven is not passed, it will be aliased to source.
 *
 * @param {string} driven
 * @param {string} [source=foo]
 */
const Example = ({ driven, source = 'foo' }) => {
  const drivenOrSource = React.useMemo(() => driven ?? source, [driven, source]);
  return <div />;
};

Example.displayName = 'Example'; // Give the anonymous function a name

// Superseded by ES5/6 prop default params
Example.defaultProps = {
  source: 'foo'
}

Example.propTypes = {
  driven: PropTypes.string,
  source: PropTypes.string
}
1
Zeeshan Arif On

You can use the the function for default prop value of driven. I am the fan of typescript so just change your code in typescript.

interface ExampleProps {
    source: string;
    driven: (props: ExampleProps) => string;
  }
  
  const Example: React.FC<ExampleProps> = ({source = 'foo', driven = source}) => (
    <div>{source} - {driven}</div>
  );
  
  Example.defaultProps = {
    source: 'foo',
    driven: function(props: ExampleProps) {
      return props.source;
    },
  };
  export default Example