skip to Main Content

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

Answers


  1. 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
    }
    
    Login or Signup to reply.
  2. 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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search