React Hook Form结合Material-UI下拉框缺失name属性问题求助
Fixing the "Missing name attribute" Error with React Hook Form Controller and Material-UI TextField
Let's break down what's causing that error and fix your component step by step:
What's Wrong in Your Current Code
- Duplicate & misplaced
nameprop: You've addedname="role"twice – once as a valid prop on<Controller>, but then again as a standalone line inside the Controller's children. That secondname="role"is just floating text, not a prop, so it's ignored. Combined with the incorrectinputRefusage, it confuses React Hook Form about the field's identity. - Incorrect use of
registerwithController: When using<Controller>, you don't need to passregisterviainputRef– the Controller handles registering the field with thecontrolprop andnameprop automatically. Using both causes conflicts and breaks the field registration flow.
Corrected Component Code
<Controller name="role" control={control} rules={{ required: true }} // Move your validation rule here render={({ field }) => ( <TextField className={classes.textField} select label="Select Role" variant="outlined" required fullWidth {...field} // Spread all necessary field props (name, value, onChange, etc.) > {roles.map(role => ( <MenuItem key={role.value} value={role.value}> {role.label} </MenuItem> ))} </TextField> )} />
Key Changes Explained
- Use
renderprop instead ofas: Therenderprop gives you explicit access to React Hook Form'sfieldobject, which includesname,value,onChangeand other critical props. Spreading{...field}onto the TextField ensures all required attributes (including thenamethe error was complaining about) are passed correctly. - Move validation rules to
Controller'srulesprop: This is the standard place to define validation when using Controller, instead of trying to useregisterdirectly. - Remove duplicate/misplaced
nameprop: The onlyname="role"you need is the one on the<Controller>itself – it gets passed down to the TextField via thefieldobject automatically. - Remove
inputRef={register(...)}: This was causing conflicts because Controller already manages field registration through thecontrolandnameprops.
After making these changes, your dropdown should work as expected, the name attribute will be properly set, and the validation error will disappear. You'll be able to access the selected role value through your form's submit handler without any issues.
内容的提问来源于stack exchange,提问作者S John
相关产品推荐
相关产品推荐

