Search code examples
react-hooksredux-form

react hooks invalid call hooks


Hello i'm trying to load a style into my ui stuff but i'm having trouble doing that

const useStyles = makeStyles(loginPage)
const classes = useStyles();
const renderTextField = ({
  label,
  input,
  meta: { touched, invalid, error },
  ...custom
}) => (

  <TextField
    label={label}
    placeholder={label}
    variant="outlined"
    InputLabelProps={{
      classes: {
        root: classes.label,
        focused: classes.focusedLabel,
        error: classes.erroredLabel
      }
    }}
    InputProps={{
      classes: {
        root: classes.cssOutlinedInput,
        focused: classes.cssFocused,
        notchedOutline: classes.notchedOutline,
      },
      startAdornment: (
        <InputAdornment position="start">
          <PersonSharpIcon style={{ fontSize: 25  , color: 'rgba(20, 176, 12,0.9)' }} />
        </InputAdornment>
      )
    }}
    error={touched && invalid}
    helperText={touched && error}
    {...input}
    {...custom}
  />
)

error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

Could someone help me how I would solve this?


Solution

  • It's exactly as the error message says. You need to move your hook inside the body of your function component.

    React considers every function starting with 'use' as a hook. So in your case it's useStyles(). React also expects such functions to be called only from inside of the body of function components and only from the root of it (so nesting it inside loops or conditional statements is a big no - you can read about it here). Your function component is renderTextField, so as you can see you're calling useStyles() OUTSIDE of renderTextField's body.

    Structuring it something like this should help:

    const useStyles = makeStyles(loginPage);
    const RenderTextField = ({
        label,
        input,
        meta: { touched, invalid, error },
        ...custom
    }) => {
        const classes = useStyles(); // <-- Move it here
        return (
            <TextField
                label={label}
                ...
            >
                ...
            </TextField>
        );
    }