Apply a static style to every rendered component just one time

Is there a way for me to individually style each card image only once? For example, I want to apply a transform style via a function in CSS; I want the image to maintain its original value, but when a new component is rendered, that card should have a different transform value applied while keeping the existing component style unchanged. Currently, all transform styles are being re-rendered with different values. Is this achievable in a functional component in React? Depending on where I place my current variable inside the Card function, all values keep changing. If placed outside of the Card function, the values remain static and the cards stack on top of each other, making only one card visible.

const getStyle = () => {
    let angle = Math.random() * 90 - 45
    let xPos = Math.random() * 40 - 20
    let yPos = Math.random() * 40 - 20
    let transform = `translate(${xPos}px, ${yPos}px) rotate(${angle}deg)`
    return transform
}


const Card = (props) => {
    let current = getStyle()
    return (
        <img style={{ transform: current }} className="Card" alt={props.name} src={props.cardImg} />
    )
}

Answer №1

One way to optimize performance in React is by using the useMemo hook.

const Card = (props) => {
    let current = useMemo(getStyle, [])
    return (
        <img style={{ transform: current }} className="Card" alt={props.name} src={props.cardImg} />
    )
}

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

Error in Gatsby Netlify build caused by @typeform/embed integration

I've been trying to embed a typeform according to the instructions provided, but even after switching to yarn package manager as recommended, I keep encountering an error during the build process. 5:27:38 PM: failed Building static HTML for pages - 4. ...

Error: When attempting to test my react-redux connected component with redux-mock-store, I encounter a TypeError stating that properties of undefined cannot be read, specifically 'getState'

I have been working on testing my function connected to a React-Redux component using `redux-mock-store`. However, I keep encountering the error message `TypeError: Cannot read properties of undefined (reading 'getState')`. Even after trying both ...

What is the reason for the discrepancy in displaying between these two arrays?

I am facing an issue where I have an array called order containing objects and another array called test that contains a string. With jQuery, I am able to output the contents of test to a <div>, but strangely I cannot do the same for the order array. ...

Get the value of an input by clicking a button in Javascript and then send a POST

I'm working on a form that has the following structure: <form method="post"> <input type="text" name="username" id="username"> <input type="text" name="password" id="password"> <select id="item" name="item"> ...

Designing a mobile user interface for time intervals

Currently, I am utilizing a datetimepicker for inputting a duration of time within a form. While the UI functions smoothly on a desktop, it struggles in a mobile setting. Despite my efforts, I have yet to discover a suitable alternative that seamlessly ope ...

What methods can I use to ensure accurate validation of dates?

I have encountered an issue with using celebrate to validate dates. Despite this, I am still able to add a start_date that is higher than the end_date. How can I prevent this behavior? Additionally, when I try to use the format 'YYYY-MM-DD', I re ...

Adding a certain number of days to a date within an existing ng-module in AngularJS

Hey everyone, I'm new to using AngularJS and I am currently attempting to incorporate one ng-module value into another ng-module date input within AngularJS. For example: if the date is 17-08-2016 and we add 20 days, the expected result should be 03-0 ...

To properly handle this file type in React, ensure you have the correct babel loader installed

https://i.sstatic.net/iNFs3.pngAn error is triggered when trying to compile with webpack. The message indicates that an appropriate loader may be needed to handle this file type. The libraries I am using are: https://i.sstatic.net/a8fXR.png Below are my ...

Utilizing React and Material-UI to create an autocomplete feature for words within sentences that are not the first word

Looking to enable hashtag autocomplete on my webapp, where typing #h would display a menu with options like #hello, #hope, etc. Since I'm using material-ui extensively within the app, it would be convenient to utilize the autocomplete component for th ...

Cannot hide the minimize/maximize button row in split pane editor layout on Eclipse Neon

Exploring the new features of Eclipse Neon has been a pleasant surprise. One notable improvement is the ability to reclaim wasted space from the UI with minimal effort. For instance, Gtk 3.20 (on Linux) has optimized scrollbars and gutters so well that cu ...

Update the object with fresh data once the XML data is transformed into JSON format

I am currently converting XML attributes into JSON format. Below is the complete function that I will explain step by step: request.execute('[someSP].[spSomeSP]', function(err, dataset) { if (err) { reject(err); } ...

Guide on uploading a 3D model in JSON format to Three JS

I am trying to import a JSON file that contains information about a 3D model for Three JS. I have the basic code structure for Three JS and also have a loader function: const loader = new THREE.ObjectLoader(); loader.load( // resource URL "mo ...

Ways to enhance the capabilities of blueprints within Sails.js without completely replacing the entire blueprint functionality

I have been struggling with a challenge for some time now, trying to implement a feature that is commonly seen in web applications. As someone who is new to sails.js and web development in general, I am open to any corrections on my use of terminology or m ...

The arrow extends just a hair below the boundaries of the div, by approximately 1 pixel

I am facing an issue with my nav bar code. In Firefox and Chrome, everything works perfectly fine - there is a small arrow displayed below the links when hovered over. However, in Internet Explorer, the arrow appears slightly below the div, causing only pa ...

Custom Bootstrap 3 Panel Organization

I'm intrigued by the layout shown in the image attached. My attempts to recreate it using a combination of columns and rows have been unsuccessful. Could it be that I'm going about this the wrong way? ...

HTML does not support the use of certain symbols

Currently, I am in the process of designing a homepage for my school project. However, I have run into an issue. The content that I want to be displayed on my homepage is as follows: "Daudzspēlētāju tiešsaites lomu spēle (Massively Multiplayer Online ...

Develop a fresh Typescript-driven sql.js database

I'm in the process of converting my JavaScript code to TypeScript. One of the libraries I rely on is sql.js. I have successfully installed the corresponding typing for it, but I am facing a roadblock when it comes to creating the database. Here is ho ...

JavaScript tip: Finding the total sum of strings with time format (e.g. 00:00:00)

I have an array that contains time values: // hours, minutes, seconds let arr = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"] Is there a way to calculate the total sum of these elements? output: "06:30:55" ...

The outcomes of array literal and array constructor methods are not consistent with each other

The distinction between array literals and array constructors may seem subtle, but it can have significant implications for your code. While the difference is often discussed, there appears to be another nuance that has not been highlighted in previous exp ...

Flickity remains in plain sight on desktop devices

I am trying to hide the flickity slider on desktop and larger devices. I have followed the instructions in the documentation, but for some reason, it's not working as expected. Here is how the div looks: <div class="w-full flex pl-4 pb-16 overflo ...