running into an issue where I'm trying to pass a prop into an MUI styled component but recieving this error when running the test suite.
Warning: React does not recognize the `charNumber` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `charnumber` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
styled component:
const StyledTextField = styled(TextField)<{ $charNumber: number }>(
({ charNumber, theme }) => ({
borderWidth: '2px',
...textAreaStyling(theme as Theme, charNumber),
})
);
When I call this styled component and give it the charNumber prop (a useState that keeps track of maxLength - typed characters ) I get the above error
where its called:
<Box>
<StyledTextField
charNumber={charNumber}
error={error}
multiline
onChange={handleOnChange}
inputProps={{ ...inputProps }}
{...props}
/>
</Box>
Any ideas on how to remove this error from occuring inside the test suite?
Related
While trying to customize the input component via MUI's InputUnstyled component (or any other unstyled component, e.g. SwitchUnstyled, SelectUnstyled etc.), I get the warning
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of `ForwardRef`.
InputElement#http://localhost:3000/main.4c2d885b9953394bb5ec.hot-update.js:59:45
div
...
I use the components prop to define a custom Input element in my own MyStyledInput component which wraps MUIs InputUnstyled:
import InputUnstyled, {
InputUnstyledProps
} from '#mui/base/InputUnstyled';
const MyStyledInput: React.FC<InputUnstyledProps> = props => {
const { components, ...otherProps } = props;
return (
<InputUnstyled
components={{
Input: InputElement,
...components,
}}
{...otherProps}
/>
);
};
My custom input component InputElement which is causing the Function components cannot be given refs warning:
import {
InputUnstyledInputSlotProps,
} from '#mui/base/InputUnstyled';
import { Box, BoxProps } from '#mui/material';
const InputElement: React.FC<BoxProps & InputUnstyledInputSlotProps> = (
{ ownerState, ...props }
) => {
return (
<Box
component="input"
// any style customizations
{...props}
ref={ref}
/>
);
});
Note: I'm using component="input to make MUI's Box component not render an HTML div but an HTML input component in the DOM.
Why am I getting this warning?
Other related questions here, here and here address similar issues but don't work with MUI Unstyled components. These threads also don't explain why
The warning wants you to have a look at the InputElement component. To be honest, the stack-trace is a bit misleading here. It says:
Check the render method of ForwardRef.
InputElement#http://localhost:3000/main.4c2d885b9953394bb5ec.hot-update.js:59:45
div
You can ignore the ForwardRef here. Internally InputElement is wrapped by
The crucial part for understanding this warning is:
Function components cannot be given refs. Attempts to access this ref will fail.
That is, if someone tries to access the actual HTML input element in the DOM via a ref (which Material UI actually tries to do), it will not succeed because the functional component InputElement is not able to pass that ref on to the input element (here created via a MUI Box component).
Hence, the warning continues with:
Did you mean to use React.forwardRef()?
This proposes the solution to wrap your function component with React.forwardRef. forwardRef gives you the possibility to get hold of the ref and pass it on to the actual input component (which in this case is the Box component with the prop component="input"). It should look as such:
import {
InputUnstyledInputSlotProps,
} from '#mui/base/InputUnstyled';
import { Box, BoxProps } from '#mui/material';
const InputElement = React.forwardRef<
HTMLInputElement,
BoxProps & InputUnstyledInputSlotProps
>(({ ownerState, ...props }, ref) => {
const theme = useTheme();
return (
<Box
component="input"
// any style customizations
{...props}
ref={ref}
/>
);
});
Why do I have to deal with the ref in the first place?
In case of an HTML input element, there as a high probability you want to access it's DOM node via a ref. This is the case if you use your React input component as an uncontrolled component. An uncontrolled input component holds its state (i.e. whatever the user enters in that input field) in the actual DOM node and not inside of the state value of a React.useState hook. If you control the input value via a React.useState hook, you're using the input as a controlled component.
Note: An input with type="file" is always an uncontrolled component. This is explained in the React docs section about the file input tag.
Let's say I'd like to render a different child component depending on which button has been clicked:
import { useState } from 'react';
const Bold = ({ text }) => (
<b>{text}</b>
);
const Italic = ({ text }) => (
<i>{text}</i>
);
export default function App() {
const [Component, setComponent] = useState();
return (
<>
<button onClick={() => setComponent(Bold)}>
Bold
</button>
<button
onClick={() => setComponent(Italic)}
>
Italic
</button>
{Component && (
<Component text="I love 🧀 more than life!" />
)}
</>
);
}
I was pretty sure this would work - I set my state item to component's function and render it. But it throws an error:
Uncaught TypeError: Cannot destructure property 'text' of '_ref' as it is undefined.
I checked if it would work without any props in children components, but no - it gives another error when there are no props:
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: . Did you accidentally export a JSX literal instead of a component?
I don't quite understand why it's happening, but I found a workaround. Instead of setting my state value directly like this:
<button onClick={() => setComponent(Bold)}>
I'm setting it through a setter function:
<button onClick={() => setComponent(() => Bold)}>
It works correctly after that change, but can someone explain why is this happening? Is having a component unpacked somewhere in the template causing problems?
The problem is that setState has two forms.
One where it accepts some object and one that it accepts a function which can work with existing state and returns the new state.
Now, when you pass a component reference, you are actually passing a function to it, and so setState assumes it is the second form, and tries to execute the function in order to get the updated state.
The workaround, as you have found out on your own, is to use the second form, passing a function that when executed will return the component you want.
I am trying to use the DatePicker component from MUI version 5. I have included it exactly as it is specified in the codesandbox example from the MUI docs. So my component looks like this:
const MonthPicker: FC = () => {
const [value, setValue] = React.useState<Date | null>(new Date());
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
views={['year', 'month']}
label="Year and Month"
minDate={new Date('2012-03-01')}
maxDate={new Date('2023-06-01')}
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(props) => <TextField {...props} size='small' helperText={null} />}
/>
</LocalizationProvider>
)
}
No matter what I tried, I always got the error message: React does not recognize the renderInput prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase renderinput instead.
If I write it in lowercase, then the code doesn't even render. What am I doing wrong here?
This is a bug from MUI, you can see it happens in the official docs too when you open the MonthPicker. It's because they forgot to filter the renderInput callback before passing the rest of the props to the DOM element.
You can see from the source that the YearPicker doesn't have this problem because it passes every props down manually, while the MonthPicker chooses to spread the remaining props which includes renderInput - this is an invalid prop because the HTML attribute doesn't know anything about JS callback object.
This error is just a warning from ReactJS when it thinks you're doing something wrong, but you're not because this is an upstream bug, and it doesn't affect anything else functionality-wise, so ignore it.
While using the MUI useMediaQuery hook, I noticed my react app being buggy and throwing errors because the hook initially does not recognise the correct breakpoint, then the page quickly re-renders with the correct value.
Example:
const mobile = useMediaQuery((theme) => theme.breakpoints.only('mobile'));
console.log(mobile)
Console:
false
true
What's going on?
This is the expected behaviour of useMediaQuery hook. It's explained in the MUI docs:
To perform the server-side hydration, the hook needs to render twice. A first time with false, the value of the server, and a second time with the resolved value. This double pass rendering cycle comes with a drawback. It's slower. You can set this option to true if you are doing client-side only rendering.
So to get the correct value on the first page render the noSsr option in the useMediaQuery hook needs to be true.
There are two options:
1) Per component:
const mobile = useMediaQuery((theme) => theme.breakpoints.only('mobile'), {noSsr: true});
2) Globally in the theme object:
const theme = createTheme({
components: {
MuiUseMediaQuery: {
defaultProps: {
noSsr: true,
},
},
}
Obviously, this will only work without server-side rendering.
The original answer below works in Material-UI v4, but the Hidden component has been deprecated in v5.
Original answer:
I realised that by removing the media query and replacing it with the Material-UI <Hidden /> component it works how I want it to.
export const ResponsiveMenuItem = forwardRef((props, ref) => {
const { children, ...other } = props;
return (
<>
<Hidden smUp>
<option ref={ref} {...other}>
{children}
</option>
</Hidden>
<Hidden only="xs">
<MenuItem ref={ref} {...other}>
{children}
</MenuItem>
</Hidden>
</>
);
});
I am using 'Material UI' Autocomplete component to render a dropdown in my form. However, in case the user wants to edit an object then the dropdown should be displayed as autofilled with whatever value that's being fetched from the database.
I've tried to mock the situation using below code
import React, { Component } from 'react';
import Autocomplete from '#material-ui/lab/Autocomplete';
import TextField from '#material-ui/core/TextField';
export default class Sizes extends Component {
state = {
default: []
}
componentDidMount() {
setTimeout(() => {
this.setState({ default: [...this.state.default, top100Films[37]]})
})
}
render() {
return (
<Autocomplete
id="size-small-standard"
size="small"
options={top100Films}
getOptionLabel={option => option.title}
defaultValue={this.state.default}
renderInput={params => (
<TextField
{...params}
variant="standard"
label="Size small"
placeholder="Favorites"
fullWidth
/>
)}
/>
);
}
}
Here after the component is mounted, I'm setting a timeout and returning the default value that should be displayed in the dropdown
However, it's unable to display the value in the dropdown and I'm seeing this error in console -
index.js:1375 Material-UI: the `getOptionLabel` method of useAutocomplete do not handle the options correctly.
The component expect a string but received undefined.
For the input option: [], `getOptionLabel` returns: undefined.
Apparently the state is getting updated when componentDidMount is getting called but the Autocomplete component's defaultValue prop is unable to read the same
Any idea what I might be getting wrong here?
Code sandbox link - https://codesandbox.io/s/dazzling-dirac-scxpr?fontsize=14&hidenavigation=1&theme=dark
For anyone else that comes across this, the solution to just use value rather than defaultValue is not sufficient. As soon as the Autocomplete loses focus it will revert back to the original value.
Manually setting the state will work however:
https://codesandbox.io/s/elegant-leavitt-v2i0h
Following reasons where your code went wrong:
1] defaultValue takes the value which has to be selected by default, an array shouldn't be passed to this prop.
2] Until your autocomplete is not multiple, an array can't be passed to the value or inputValue prop.
Ok I was actually able to make this work. Turns out I was using the wrong prop. I just changed defaultValue to value and it worked.
Updated code pen link - codesandbox.io/s/dazzling-dirac-scxpr