Tips for ensuring the accurate retrieval of prop values by waiting for the value to be set

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!

Answer ā„–1

One way to achieve this is by

return (
    icon && (<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>)
  );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show the outcome stored within the const statement in TypeScript

I am trying to display the outcome of this.contract.mint(amount, {value: this.state.tokenPrice.mul(amount)}) after awaiting it. I want to see the result. async mintTokens(amount: number): Promise<void> { try { let showRes = await this.c ...

Avoiding external variable reference through Jest.mock

For snapshot testing, I need to create a simple dummy mock of 1 react component. When attempting to use React.Component within the mock function, an error is thrown: The second argument of jest.mock() cannot reference external variables. However, usin ...

Manipulate the <title> tag using jQuery or PHP

I have my own personal blog and I am trying to change the title tag dynamically when viewing different blog posts. My goal is to have the post title show up in the Twitter tweet button. I attempted the following methods: <script type="text/javascript"& ...

Text with background coloring only

My text background always extends beyond the screen. Can anyone help me figure out what I'm doing wrong? Here is the HTML code: <div class="textSlide"> <span id="firstTitle">We assist you in finding all the individu ...

What is the best way to incorporate a unique box shadow onto my svg image?

While I've seen a similar question here: How to add box-shadow to a svg path circle shape, I am struggling to grasp how the transition from box shadow characteristics to SVG drop shadow characteristics was achieved. (Especially given that SVG Drop sha ...

Tips for getting my navigation bar menu button functioning properly?

I am struggling to make my button show the menu when clicked. I have tried various methods but still can't pinpoint the issue. I utilized the "checkbox" trick to display the hamburger button when the site width is under 500px for a responsive menu, ye ...

What are the optimal strategies for managing various components within an Angular (2) Web application?

I am seeking advice on Angular 2+ Webapps and have a few questions. What is the recommended approach for managing a publicly available info page, an authentication page, and a protected page for signed-in users? Should I consider separate Angular Apps ...

Having trouble retrieving a specific object from an array using EJS

When re-rendering my form with any errors, I am able to display the errors in a list. However, I would like to access each error individually to display them under the invalid input instead of all at the bottom of the form. Here is what I have tried so f ...

Using JavaScript's Regex to match sentences, while ensuring any full stops within quotes are ignored

Here is the regular expression: (?:(?:Jr|Master|Mr|Ms|Mrs|Dr|Capt|Col|Sgt|Sr|Prof|Rep|Mt|Mount|St|Etc|Eg)\.\s+|["'ā€œ(\[]?)(?:\b(?:(?!(?:\S{1,})[.?!]+["']?\s+["']?[A-Z]).)*)(?:(?:(?:Jr|Master|Mr|M ...

Problem with Google+ Button Alignment

I arranged my social media buttons in a row - Twitter, Facebook & Google+. The issue is that the Google+ button is not aligning properly. It appears to be spaced out about 3 times further than the Twitter and Facebook buttons. I attempted adjusting the p ...

Retrieve the heading of a click-able element using jQuery

My challenge involves a list of selectable buttons with names generated dynamically from a JSON file. Each time a button is clicked, I aim to retrieve its title, which corresponds to row["name"]. Below is my relevant code snippet and the JSON data provided ...

Is there a way to display current data in angularJS based on the current time?

My database contains timestamps like 2016-12-30 00:30:10 which I retrieve using the $http module in Angular. Below is a snippet of my Angular code: angular .module('sampleApp') .controller('ReportCtrl', ReportCtrl) ...

My lists are not being styled by Embedded and Internal CSS

I want the ingredients list to be styled in green, equipment list in red, and method list in blue using different CSS techniques. My external works fine for changing the color to red, but my internal styles don't seem to apply to the other lists. < ...

Verifying changes using Cypress transformations

I'm brand new to using Cypress and I am currently attempting to verify that one of my elements contains a specific style. The element in question looks like this: <div class="myElement" style="transform: translate(0%, 0px); "></div> Her ...

Ways to identify when a React child element is overflowing

tl;dr How can I create a component that hides overflow and toggles views with a button? For example, the user can initially see tabs 1, 2, and 3 while tabs 4, 5, and 6 are hidden. Clicking a button will hide tabs 1, 2, and 3, and show tabs 4, 5, and 6 with ...

pick out particular values from an array

I have a question that may seem basic to some, but I'm curious about how to select specific elements from an array. In this case, I have an array with 100 elements: var cubes = [element1, element2, element3 ...] and I want to select elements 25-35. ...

Advantages of utilizing bracket notation (alongside variables) for retrieving a property from an object

When it comes to accessing stored information, utilizing alternatives like the dot operator can be straightforward. However, Iā€™m struggling to grasp the significance of using variables in achieving the same goal. For instance: var myObj = { prop1: "v ...

Please provide values in the input box, with each value separated by

I attempted the following code: success: function (result) { for (var i = 0; i < result.d.length; i++) { var emails = new Array(); emails = result.d[i].Emailid; alert(emails); $("#EmailCC").val(emails); ...

The JSON format in ASP.Net Core MVC does not have designated data fields

I am currently facing an issue with my JavaScript code related to cascading dropdowns. The setup involves having one dropdown for selecting a car brand and another dropdown for choosing a specific model under that brand. The functionality should work in su ...

Create a list with interconnected input fields for duplication

I'm new to javascript and I have a question. I'm working on duplicating a list that has input fields for each option. The duplication is working fine, but the associated input fields are not showing up in the duplicated list. Additionally, I woul ...