Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass custom props to Redux Form Field in TypeScript

Tags:

I want to pass custom properties to my Redux-Form-Field. In the documentation it says:

Any custom props passed to Field will be merged into the props object on the same level as the input and meta objects.

But passing a custom prop to the Field component will throw a compile error:

<Field
    name="E-Mail"
    component={MaterialTextField}
    myProp="Test"
/>

Property 'myProp' does not exist on type '(IntrinsicAttributes & IntrinsicClassAttributes> & ...

Inside the props attribute I can only add a predefined set of properties like placeholder or type. Passing another prop will throw this error:

<Field
    name="E-Mail"
    component={MaterialTextField}
    props = {{
        myProps: 'Test'
    }}
/>

Type '{ name: "E-Mail"; component: (props: any) => Element; props: { myProps: string; }; }' is not assignable to type '(IntrinsicAttributes & ...

Is there a possibility to pass custom props to the Field component in TypeScript?

like image 295
Deutro Avatar asked Sep 08 '17 07:09

Deutro


Video Answer


2 Answers

To pass custom props to Field component of Redux Form, you need to declare an interface of all the props you want to pass.

interface YourCustomProps {
    myProp1: string;
    myProp2: number;
}

Now, use GenericField from Redux Form to make Field as YourCustomField to which you will be able to pass YourCustomProps

import { Field, GenericField } from 'redux-form';

const YourCustomField = Field as new () => GenericField<YourCustomProps>;

Now you can pass custom props to YourCustomField as declared in the interface.

<YourCustomField
    myProp1="Hi"
    myProp2={123}
    component={MaterialTextField}
/>

This way you can pass anything as custom props such as react components as well! :)

like image 30
Vinay Sharma Avatar answered Sep 20 '22 13:09

Vinay Sharma


After some more experimenting on my side I found a solution to pass custom props:

<Field 
    name="myName"
    props={{
        type: 'text'
    }}
    component={myComponent}
    {...{
        myCustomProps1: 'myCustomProp1',
        myCustomProps2: 'myCustomProp2'
    }}
/>

In myComponent you have your custom props on the root level of your properties:

const myComponent = (props) => {
    return <div>{props.myCustomProp1 + " " props.myCustomProp2}</div>
}
like image 184
Deutro Avatar answered Sep 18 '22 13:09

Deutro