Search code examples
reactjsmaterial-uiredux-form

name prop going as undefined


I am using redux-form and I sent TextField of material-ui as prop to Field of redux-form. But the other properties are going perfectly as expected.

<Field
    id="firstName"
    name="firstName"
    floatingLabelText="Username"
    errorText={this.state.firstNameError}
    component={TextInputField}
/>

Below code it the TextInputField component

import React from 'react';
import PropTypes from 'prop-types';
import TextField from 'material-ui/TextField';
import _noop from 'lodash/noop';

const TextInputField = ({
    hintText,
    id,
    name,
    className,
    defaultValue,
    floatingLabelText,
    errorText,
    onFocus,
    onChange,
    onBlur
}) => {

return (
    <TextField
        hintText={hintText}
        id={id}
        name={name}
        className={className}
        defaultValue={defaultValue}
        floatingLabelText={floatingLabelText}
        errorText={errorText}
        onFocus={onFocus}
        onChange={onChange}
        onBlur={onBlur}
    />
);
};

export default TextInputField;

The problem here is name prop is coming as undefined in the place where I used the component.I don't know where this is happening. When I consoled the name prop it is coming as undefined.


Solution

  • Your TextInputField is supposed to accept input and meta props according docs. input prop has name attribute.

    From redux-form docs:

    The props provided by redux-form are divided into input and meta objects.

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

    Here is a quote from input props section:

    input.name : String When nested in FormSection, returns the name prop prefixed with the FormSection name. Otherwise, returns the name prop that you passed in.

    So your component should look like this:

    const TextInputField = ({
        input: { 
          name,
          onChange,
          onBlur,
          onFocus
        },
        hintText,
        id,
        className,
        defaultValue,
        floatingLabelText,
        errorText
    }) => (
      <TextField
          hintText={hintText}
          id={id}
          name={name}
          className={className}
          defaultValue={defaultValue}
          floatingLabelText={floatingLabelText}
          errorText={errorText}
          onFocus={onFocus}
          onChange={onChange}
          onBlur={onBlur}
        />
    );
    

    or even simpler:

    const TextInputField = ({ input, meta, ...rest }) => (
      <TextField {...input} {...rest} />
    );