How to pass an object of an interface and some other type to functional component in React?

Viewed 1158

Let's say I have an interface

interface Setting {
    desc: string,
    title: string,
    value: string | number | boolean | number[] | float,
    value_type: "string" | "integer" | "bool" | "list" | "float"
}

And a functional component that accepts two arguments

const SettingsOption = ({ ...option }: Setting, test: string): JSX.Element => {return (...)}

Such function signature seems fine to TypeScript compiler.

Next, I try to call the component using <SettingsOption {...option} test=""/> but it says

type '{ test: string; desc: string; title: string; value: string | number | boolean | number[]; value_type: "string" | "float" | "integer" | "bool" | "list"; }' is not assignable to type 'IntrinsicAttributes & Setting'.
  Property 'test' does not exist on type 'IntrinsicAttributes & Setting'.ts(2322)

My question: is there a way to call such component with passing all necessary information?

2 Answers

You must notice to some points.

  1. In React functional components, first parameter is component props and second is Forwarding refs to DOM components.
  2. All properties you pass in JSX element will receive as porps in component.

So you can't have test for second parameter. Also if you use test as properties in JSX element, SettingsOption will get it in props. Because of this you get that error.

interface Setting {
    desc: string,
    title: string,
    test: string;
    value: string | number | boolean | number[] | float,
    value_type: "string" | "integer" | "bool" | "list" | "float"
}
const SettingsOption = ({ ...option }: Setting): JSX.Element => {return (...)}

Alternatively instead of using the functional component as element, you can call it as function and pass all necessary arguments:

return (
    <div>
        {SettingsOption(option, "test")}
    </div>
)

But this approach may cause to rise Rendered more times than during previous render if your component uses hooks.

You can't do this because first param is props object and the second param is reference for React.forwardRef API. But you can use rest operator, example:

interface Setting {
    desc: string,
    title: string,
    value: string | number | boolean | number[] | float,
    value_type: "string" | "integer" | "bool" | "list" | "float",
    test: string
}
const SettingsOption = ({test, ...option }: Setting): JSX.Element => {return (...)}

Related