Ways to generate a distinct identification number for every element within a component instance

I have a ReactJS component that I use in multiple instances. I'm trying to change the CSS elements of each component on click.

Initially, I tried referencing the specific component element by ID, but the issue is that all instances currently share the same ID, causing changes to affect all components.

I'm considering passing a unique reference to each component, but I'm unsure how to implement this in the HTML IDs of the elements. In Angular, a solution would look like this:

<span id="{{ 'object-' + $component_idx }}"></span>

Is there a similar approach in React? Or perhaps a better way to achieve my goal?

This is what I am currently doing:

Calling the component instance in the parent:

<Entry
    title={instance_title}
    number={i}
  />

Creating an Entry component:

class Entry extends React.Component {
  constructor(props) {
    super(props);
    this.state = { preference: 4 };
  }


preferencer(idx) {
    // Change emoji size
    let oldPref = this.state.preference;
    if (idx == this.state.preference) {
      this.state.preference = 4;
      document.getElementById("emo" + idx).style.transform = "scale(1)";
    } else if (idx != this.state.preference) {
      this.state.preference = idx;
      document.getElementById("emo" + idx).style.transform = "scale(2)";
      if (oldPref != 4) {
        document.getElementById("emo" + oldPref).style.transform = "scale(1)";
      }
    }
  }


  render() {
    return (
      <Wrapper>
        <EmojiWrap id="emo0" onClick={() => this.preferencer(0)}>
           🤢{" "}
         </EmojiWrap>
         <EmojiWrap id="emo1" onClick={() => this.preferencer(1)}>
           😶
         </EmojiWrap>
         <EmojiWrap id="emo2" onClick={() => this.preferencer(2)}>
           😍
        </EmojiWrap>
      </Wrapper>
     );
    }
 }
export default Entry;

Thank you!

Answer №1

To simplify your code and avoid using IDs for styling purposes, you can utilize a conditional checker within the styles property. By directly changing the state onClick, you can achieve this effect:

<EmojiWrap style={this.state.preference === 1 ? {transform: "scale(2)"} : {}} 
onClick={() => this.setState({preference: 1})} >
...
</emojiWrap>

//repeat this process for each emoji by updating the number and emoji content

This approach eliminates the necessity for the preferencer function.

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

Ways to schedule the execution of a script at a specific time using Node.js

Every time the readDirectory function is called, it checks if any file created date is more than 30 days ago and removes that file from the directory. While this functionality is working correctly, I am concerned about its efficiency. To address this issue ...

Checking time differences in MongoDB

Here is the data from my mongodb document: [ { startTime: "08:00", endTime: "09:00", id: 1 }, { startTime: "08:10", endTime: "09:00", id: 2 }, { ...

The browser mistakenly sends a GET request instead of a POST request

I've created a JavaScript function that sends POST requests similar to an HTML form. The function implementation is as follows: function sendPostRequest(url, data) { var $form = $('<form action="' + withContext(url) + '" method= ...

Utilizing Normal Mapping with ShaderMaterial, TangentSpace, and fromGeometry in Three.js

I've been struggling to understand normal mapping with Three.js. Despite my efforts, I can't seem to get it right. Below is the code I've been working on: Javascript: var bufferGeometry = new THREE.BufferGeometry(); bufferGeometry.fromGeo ...

What are the limitations preventing C++ applications from generating interfaces similar to those of PHP, HTML, and CSS?

I've always been puzzled by the fact that programming languages such as C++, Python, C, and others seem to be stuck in the realm of the command line. When building websites, I can easily use HTML, CSS, and PHP to quickly create both the logic and inte ...

Unchecked box in the map is not being marked

I'm currently learning how to use React and experimenting with creating a todo app using React hooks. I have a todoList array that I am displaying in an unordered list, with a checkbox for each todo item. The issue I'm facing is that the checkbox ...

Which is more advantageous: returning a value or returning a local variable?

While the title may not be the best descriptor in this situation, I am unsure of how to phrase it any better. Both of these functions perform the same task: function A(a, b) { return a * b; } function B(a, b) { var c = a * b; return c; ...

What is the best way to ensure text starts on a new line when paragraphs and images are floating and aligned?

Does anyone have a clearer title idea? Feel free to edit. To better illustrate my point, I've created a jsfiddle. I am working with a simple layout of text and images. My goal is to make the second text and image appear on a new row just below the f ...

What is a way to ensure that an event is constantly activated when hovering over a specific element?

Currently, I am facing a scenario where I have a button and I need an event to continuously trigger while the button is being hovered. Unfortunately, using the mouseover method only causes the event to fire once when the cursor initially moves over the but ...

The functionality of Dompdf's style does not seem to be functioning properly

I've been experimenting with dompdf and while my script successfully generates a PDF document, the style tag seems to have no effect. Here's my code. I'm familiar with how it operates and have used it with pure HTML before, but this is my fi ...

jQuery: Gallerific Partially Functioning

Currently, I am attempting to implement the jQuery gallerific plugin on my website located at . The gallery loads correctly, however, both the thumbnail grid and navigation buttons for next/previous images are not functioning as expected. Despite no visi ...

What is the best way to initialize a React project on my local machine using files obtained from a server?

Looking to work on an existing React app on my local machine, but the only files I have are uploaded to the server public_html. Directory view I can provide access to the root folder where all the files are located. Is it feasible to set up the React pro ...

Manipulating AngularJS variables that are outside of its designated scope should be restricted

Something strange is happening in my code. I created a function called "insertTstData" outside of any angular scope, and when it is called from another function named "save" within a controller named "remark", it somehow manipulates a local variable and th ...

Is there a way to adjust paragraph sizes in CSS flexbox so they scale with the font size?

After spending hours trying to figure this out on my own, I finally caved and registered on StackOverflow. Despite Google providing plenty of related questions and examples, I still can't find a solution to my specific problem. The issue at hand is c ...

Issues with Node.js and Socket.io: Receiving error "Cannot read property 'on' of undefined"

I've encountered an issue while trying to establish a websocket connection using socket.io and node.js. Here is the setup I'm working with: Operating System: Windows 7 Node version: 6.9.2 NPM version: 4.0.5 Packages: "express": "^4.14.0" "soc ...

Encountering an issue while trying to import the validator module in NextJS 13

I encountered a peculiar issue while trying to import a module. Nextjs presented the following error message: ./application/sign_in/sign_in_store.ts:2:0 Module not found: Can't resolve 'validator' 1 | import { createEvent, createStore } fr ...

Error displayed inline

I am facing an issue with a hidden textbox that I need to make visible based on a certain condition. Despite checking that the control is being triggered by the change event, I am unable to get it to display. I have experimented with different methods with ...

JavaScript: Generating multiple variables using a for loop?

Is there a way to dynamically create n variables a_1, a_2, a_3 ... a_n, where the value of n is determined during runtime? Attempting to use the following code would not produce the desired outcome: var n = prompt("Enter number of variables?"); for (i= ...

"Unlocking Privileges: Delving into Access Tokens, Refresh Tokens, and

I have implemented a JWT authentication scheme for my application. After conducting research on storing and utilizing access and refresh tokens, I still have some unanswered questions. My frontend is built with React and my backend is using .NET 6 Web API. ...

Steps for incorporating a personalized action menu into a material table

Currently, I am trying to showcase a menu within the actions column on material-table. I came across a related post here: How show menu item in Material Table that provides a solution, but unfortunately I am unable to access the sandbox for testing and exp ...