Encountering an issue with the .toUpperCase() method within one of my components, resulting in the following error:
TypeError: Cannot read properties of undefined (reading 'toUpperCase')
This problem seems to stem from a race condition in fetching the prop within my reusable component named Icon, occurring roughly 50% of the time upon page refresh.
import React from 'react';
import PropTypes from 'prop-types';
import './icons-svg-color.css';
const Icon = (props) => {
const { icon, className } = props;
return (
<div className={`icon-32 ${className}`} style={{ backgroundImage: `url('data:image/svg+xml;utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><style>.text {font-family: sans-serif; font-size: 10px; fill:%23FFF;}</style><circle class="cls-1" cx="16" cy="16" r="16" fill="%231d5baa"/><text x="50%" y="63%" text-anchor="middle" class="text">${icon.toUpperCase()}</text></svg>')` }}>
<div className={`icon-32 ${className}`} style={{ backgroundImage: `url(/static/images/assets/icons/svg/color/${icon}.svg)` }} />
</div>
);
};
Icon.defaultProps = {
className: '',
};
Icon.propTypes = {
icon: PropTypes.string.isRequired,
className: PropTypes.string
};
export default Icon;
Usage of this component is as follows:
const renderMenuItems = () => {
return chartMarkets.map((type) => {
return (
<MenuItem value={type} onClick={event => handleSelection(event)}>
<Icon className={classes.menuItemImage} icon={type} />
<Typography variant="body1">{type}</Typography>
</MenuItem>
);
});
};
I've attempted solutions such as setting default values to empty strings, without the desired outcome as the app no longer crashes but the icon is missing. Also tried conditional rendering by passing the value into the prop after it's defined like so:
<MenuItem value={type} onClick={event => handleSelection(event)}>
<Icon className={classes.menuItemImage} ***icon={type && type}*** />
<Typography variant="body1">{type}</Typography>
</MenuItem>
However, the program still crashes with the same error. I've also experimented with incorporating useEffect in the reusable Icon component like this:
useEffect(() => {
}, [icon]);
Are there any other potential solutions that I can explore? Thank you!