简体   繁体   中英

Optional property on a component?

I am trying to render a component that must have one of its properties be optional, like it either is there with a value, or its not there at all:

export default function Select({ListBoxProperty}) {

  return (ListBoxProperty ? <Component ListBox={ListBoxProperty} /> : <Component />)
}

If ListBoxProperty is undefined, the ListBox property should not be given to Component at all.

How can I do the above without the ternary operator, and do it within the properties of Component ?

Not sure if this counts as "without the ternary operator" if it's outside of the line where you're creating <Component> , but here is a way that you can conditionally pass properties to a component:

export default function Select({ListBoxProperty}) {
    const propertiesToSend = {
        ...(ListBoxProperty ? { ListBox: ListBoxProperty } : null),
    };

    return <Component {...propertiesToSend} />
}

Example:

import React from 'react';

interface ComponentProps {
  ListBox: unknown;
}

function Component(props: ComponentProps) {
  return <>foo</>;
}

export interface SelectProps {
  ListBoxProperty?: unknown;
}

function Select(props: SelectProps) {
  return (
    <>
      {props.ListBoxProperty &&
        <Component ListBox={props.ListBoxProperty} />
      }
    </>
  );
}

If it's necessary to return null then use ternary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM