React JS issue with SVG linearGradient not displaying accurate values

Within my component, I am working with SVG paths and a linearGradient value passed down from the parent component through static data. The properties 'startColor' and 'stopColor' are used to define the gradient colors for each element.

Even though the values logged for each object are correct, they do not display as expected on the screen. It appears that the first value from the initial object is being applied to all components during rendering. I have verified this behavior through testing.

I am looking for a solution to ensure that each circle renders with the correct gradient colors specified in the data.

Data structure:

    const dataOne = [
    {
        title: 'Cpu utilisation',
        graph: 65,
        noBorder: false,
        noMargin: false,
        startColor: '#2DC0FF',
        stopColor: '#0160B2'
    },
    {
        title: 'Memory utilisation',
        graph: 65,
        noBorder: true,
        noMargin: true,
        startColor: '#2DC0FF',
        stopColor: '#0160B2'
    },
]

const dataTwo = [
    {
        title: 'Warnings today',
        graph: 65,
        noBorder: false,
        noMargin: false,
        startColor: '#fa9100',
        stopColor: '#ffc14f'
    },
    {
        title: 'Errors today',
        graph: 65,
        noBorder: true,
        noMargin: true,
        startColor: '#fa9100',
        stopColor: '#ffc14f'
    },
]

Component usage:

<div className="tab-info-body large">
    <DoubleGraph data={dataOne} />                              
</div>
<div className="tab-info-body large">
    <DoubleGraph data={dataTwo} />                              
</div>

Component code:

render() {
        const { data, title, startColor, stopColor } = this.props;
        const { value, valueOne, valueTwo, hidden, visible, valueOneYPos, valueTwoYPos, valueOneHidden, valueTwoHidden, dashArray, dashArrayBorder } = this.state;
        const styleOne = { transform: `translate(0px, ${valueOneYPos}px)` };
        const styleTwo = { transform: `translate(0px, ${valueTwoYPos}px)` };

        return (
            <div className="double-graph-wrap">
                <div className="flex">
                    {data.map((item, i) => {
                        console.log("give me colour", item.startColor)
                        return (
                            <div className={classNames('wrap', { noBorder: item.noBorder, noMargin: item.noMargin})}>
                                {i === 1 &&<div className="border-test"></div>}
                                <span className="title">{item.title}</span>
                                <div className="graph-wrap">
                                    <div className="graph">
                                        <div className="value-wrap">
                                            <div className="values">
                                                <span style={styleOne} className={classNames("valueOne", {hidden: valueOneHidden})}>{valueOne}</span>
                                                <span style={styleTwo} className={classNames("valueTwo", {hidden: valueTwoHidden})}>{valueTwo}</span>
                                            </div>
                                        </div>
                                        <div class="single-chart">
                                            <div style={{ background: 'black', width: 100, height: 100}}>{item.startColor}</div>
                                            <svg viewBox="0 0 36 36" class="circular-chart orange">
                                            <defs>
                                              <linearGradient id='grad'>
                                                <stop stop-color={item.startColor} />
                                                <stop offset='100%' stop-color={item.stopColor} />
                                              </linearGradient>
                                              </defs>
                                                <path class="circle-bg"
                                                    d="M18 2.0845
                                                    a 15.9155 15.9155 0 0 1 0 31.831
                                                    a 15.9155 15.9155 0 0 1 0 -31.831"
                                                />
                                                    <path class="borderTwo"
                                                    stroke-dasharray={dashArrayBorder}
                                                    d="M18 2.0845
                                                    a 15.9155 15.9155 0 0 1 0 31.831 
                                                    a 15.9155 15.9155 0 0 1 0 -31.831"
                                                />
                                                <path class="circle"
                                                    stroke-dasharray={dashArray}
                                                    d="M18 2.0845
                                                    a 15.9155 15.9155 0 0 1 0 31.831 
                                                    a 15.9155 15.9155 0 0 1 0 -31.831"
                                                />
                                                <path class="borderOne"
                                                    stroke-dasharray="1, 100"
                                                    d="M18 2.0845
                                                    a 15.9155 15.9155 0 0 1 0 31.831 
                                                    a 15.9155 15.9155 0 0 1 0 -31.831"
                                                />
                                                <path class="average"
                                                stroke-dasharray="1, 100"
                                                    d="M18 2.0845
                                                    a 15.9155 15.9155 0 0 1 0 31.831"
                                                />
                                            </svg>

                                        </div>
                                    </div>
                                </div>
                            </div>
                        )
                    })}
                </div>
            </div>
        )
    }

Answer №1

I came across this same issue and found that the solution mentioned by Filth really saved the day for me.

The main problem lies in the fact that the browser requires unique ids. The outcome can vary depending on the browser being used (we observed differences between chrome and safari).

If you have identical ids (check it out here), all circles will display the same color gradient in chrome version 83.0.4103.97 on debian operating system.

You can identify this by running document.getElementById("yourid") and noticing that the element is shared among all gradients.

Just a heads up: I added a fill to simplify things.

<path
class="average"
stroke-dasharray="1, 100"
d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831"
fill={`url(#${item.id})`}

To resolve this issue, simply make sure to use a unique id for the fill see it in action here

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

Guide on how to automatically direct users to a page upon successful login in ReactJS

How can I redirect to the homepage after a successful login in ReactJS? Also, how can I display an error message when a user enters incorrect credentials? I have attempted the following code, but it does not successfully redirect to the homepage or show ...

Display icon on two separate rows in a Material-UI table

I am working with a React Material-UI table where I have two adjacent rows that are related at times. I would like to display a chain icon (or something similar) between these connected rows. I have provided a rough sketch below: https://i.sstatic.net/7FA ...

I'm a beginner when it comes to working with MongoDB and I'm looking to insert a new field into a specific document. Can anyone advise me on how to accomplish this using Node

As an illustration, consider a document structured as follows: {_id:1, name:"John" } If a new field is added, the document will be updated to: {_id:1, name:"John", last_name:"doe" } ...

The page is being enhanced with FontAwesome Styles through React rendering

I have managed to successfully incorporate various FontAwesome icons into my React App. However, I am facing an issue where the raw CSS styles from FontAwesome are also being rendered at the top of my page. Upon inspecting my page, I noticed a style elemen ...

What does the reportProgress function do in HTTP services with JavaScript?

Can someone explain the functionality of reportProgress in JavaScript, specifically when used with Angular Typescript? I am having trouble finding documentation on this. return this.httpClient.request<ProductResponse>('get',`${this.basePath ...

Redirect Conditions in NextJS

One scenario: a blog with an extensive library of content cataloged by Google. Every piece is accessible via www.site.com/post1. When migrating this blog to NextJS, the posts are now located at www.site.com/blog/post1. Redirects using 301 have successful ...

Transitioning JS/CSS effects when the window is inactive

My latest project involved creating a small slider using JavaScript to set classes every X seconds, with animation done through CSS Transition. However, I noticed that when the window is inactive (such as if you switch to another tab) and then return, the ...

Utilizing lodash to Filter Arrays Within Arrays

Let's take a look at the JSON structure provided below. comapany : ABC Emp Info:[ { empName: D, empID:4 salary[ { year: 2017, ...

What is the best way to reduce the file size of a group of PNG images for

For my game character, I have a collection of PNG files including stand.png, run1.png, run2.png. To display a series of actions on the JavaScript canvas, I need to load these images. However, the size of each .png file adds up quickly – for example, it ...

The Design and Layout of a MEAN Stack Application

When creating a MEAN Stack app using the express-generator npm, everything worked perfectly but I found myself confused about the purpose of certain files. For instance: The package.json included this code snippet: "script":{"start": "node ./bin/www"} ...

React Hooks findByID method is throwing an error stating that it cannot read the property 'params' because it is undefined

As I dive into learning React hooks, I'm realizing that it's crucial to stay up-to-date with the latest trends in web development. Despite hours of research and tinkering around, I can't seem to wrap my head around some key concepts. The fac ...

Is it possible to transfer .NET backend functions to a frontend framework like React or Vue for client-side execution?

For instance, imagine a scenario where there is a login page requiring a username and password to meet specific criteria for validation: the username must contain a capital 'A' and the password should be exactly 8 characters long. The challenge l ...

How can I prevent the browser's back button from functioning on an AngularJS webpage?

Is there a way to disable the browser's back button and refresh button in Angular? For example, in my source code: Page Source: "use strict"; .controller("wizardSecondController", function($scope, $state, $stateParams, wizardManager) { $scope.$on ...

use javascript or jquery to conceal the textbox control

Looking to conceal a textbox control using javascript or jquery. I attempted the following code: document.getElementsByName('Custom_Field_Custom1').style.display="none"; Unfortunately, I received an error in the java console: document.getEle ...

Troubles with double borders in HTML's opaque border feature

I'm encountering an issue where opaque borders are overlapping each other, causing the alpha value to be twice as high as intended. This problem seems to only affect the first n-1 elements — the last child is rendering correctly. Check out the Cod ...

Guide on redirecting to a specific tab data target in Symfony 5

When a user is on the 3rd tab and clicks on a DELETE button, I want to redirect the user back to the same 3rd tab on the page. **Template:** <nav> <ul class="nav nav-tabs"> <li class="nav-item"> ...

Angular 7 router navigate encountering a matching issue

I created a router module with the following configuration: RouterModule.forRoot([ {path: 'general', component: MapComponent}, {path: 'general/:id', component: MapComponent}, {path: '', component: LoginComponent} ]) Sub ...

The scrolling experience in Next js is not as smooth as expected due to laggy MOMENTUM

Currently, I am in the process of constructing my portfolio website using Next.js with Typescript. Although I am relatively new to both Next.js and Typescript, I decided to leverage them as a learning opportunity. Interestingly, I encountered an issue with ...

Tips for managing modal states in functional React components in React Native using React hooks

Utilizing React hooks to manage modal opening and closing, I encountered an issue with my code. The function 'handleAddClick' is supposed to open the modal when used on TouchableOpacity, while the function 'handleClose' should close the ...

Creating impenetrable div elements with JavaScript or jQuery

I'm currently working on creating solid blocks using DIVs positioned side by side both horizontally and vertically. I've successfully achieved this when the divs have equal heights. However, an issue arises when a div has larger dimensions; it en ...