In the following code:
import React from 'react';
import {
Avatar, Menu, MenuItem, Tooltip, Box,
} from '@mui/material';
import PropTypes from 'prop-types';
// eslint-disable-next-line no-unused-vars
import { positions } from '@mui/system';
const menuItems = ['Test', 'Yes', 'No'];
function PositionedMenu(props) {
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const { boxStyle: PropTypes.object} = props;
...
I am getting the following error in the specific position - PropTypes.object (where I validate boxStyles): Parsing error: Unexpected token, expected ",".
Why is this happening? I'm using React with eslint set to airbnb options.
CodePudding user response:
You can pass boxStyle parent to child component and use it.
// Parent component
function ParentComponent(props) {
render(
<childComponent boxStyle={{ background: 'red'}} />
)
}
// Child Component
function childComponent(props) {
const { boxStyle } = props;
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
}
childComponent.propTypes = {
boxStyle: PropTypes.object
};
CodePudding user response:
You are destructuring on that line, if you want to set default value, you need to use = char and not :
const { boxStyle = PropTypes.object} = props;
And yes, this is not the way to set propTypes. Here's example from docs:
Class based:
import PropTypes from 'prop-types';
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Greeting.propTypes = {
name: PropTypes.string
};
Function based:
import PropTypes from 'prop-types'
function HelloWorldComponent({ name }) {
return (
<div>Hello, {name}</div>
)
}
HelloWorldComponent.propTypes = {
name: PropTypes.string
}
export default HelloWorldComponent
Sometimes when setting up props we think that prop is only of type object. But due to a lot of factors (for example, how we fetch data and set props) a prop can be undefined for an initial period of time (very short) and then be defined as an object once the data is loaded.
To avoid you can either:
Change the way the data is supplied and therefore make sure that the prop is always an
objectAllow in propTypes for both values:
undefined(for initial moment) and thenobjectas well once it loads. Here's how to specify multiple propTypes (without the use of default props):
// An object that could be one of many types
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
]),
