Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux form - adding dynamically prop name to FormSection

I am wondering how can I add a name to a form section dynamically instead of having a static name like in this example. I have tried something like this:

class Address extends FormSection {

    render() {
        return <div>
            <Field name="streetName" component="input" type="text"/>
            <Field name="number" component="input" type="text"/>
            <Field name="zipCode" component="input" type="text"/> 
        </div>
    }
}

Address.PropTypes = {
  name: PropTypes.string.isRequired,
};

I am calling this component from my parent component that is connected to redux-form like this:

  <Address
    name={formSectionName}
  /> 

But, nothing gets rendered, I am suppose to toggle this with the radio button, but the component never gets rendered. How can I do this, and set the name of the FormSection dynamically?

like image 880
Leff Avatar asked Jun 19 '26 05:06

Leff


1 Answers

Class inheritance in Javascript is a bit tricky, but I don't want to go into detail here.

But what I see is that the listed example of Inheritance, comes with a caveat of not making it possible to change the name: https://redux-form.com/7.4.2/docs/api/formsection.md/#example-usage

"For component such as Address that rarely change form section name it can be benificial to make the component inherit from FormSection instead of Component and set a default name prop as seen below"

From what I see is that by doing it via inheritance, you cannot longer use an outer prop to control it, but rather use the static default prop...

My personal opinion on this example is that I find it a bit confusing to be honest. There is also an open issue on github for this exact problem: https://github.com/erikras/redux-form/issues/4359

But why don't you go for this approach? I would solve it by composition.

class Address extends React.Component {

    render() {

        const { name } = this.props;

        return (
           <FormSection name={name}>
            <div>
              <Field name="streetName" component="input" type="text"/>
              <Field name="number" component="input" type="text"/>
              <Field name="zipCode" component="input" type="text"/> 
            </div>
          </FormSection>
         )
    }
} 
Address.propTypes = {
  name: PropTypes.string.isRequired,
};
like image 70
larrydahooster Avatar answered Jun 21 '26 20:06

larrydahooster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!