Update the selected item by making changes to it using the specified method name, ensuring that only that specific item

I currently have multiple divs displaying various details. My initial plan was to fetch the details from the backend and bind them to my HTML section, but for now, I have hardcoded the details. Here is a snippet of my HTML code:

<div className="trait_box polaroid" onClick={this.trait_select}>
  <div className="main_trait_card" style={{transform: this.state.rotated ? 'rotateY(180deg)' : 'none' }}>
    <div className="front_card_rotate">
      <div className="trait_description_div">
        <span className="trait_description">Honesty</span>
      </div>
      <div className="trait_img_div">
        <img src={Honesty} className="trait_img"/>
      </div>
      <div className="block__body">
          <img src={Add} className="trait_add"/>
            <p className="trait_text">Honesty refers to a facet of moral character and connotes positive and virtuous attributes such as integrity, truthfulness, straightforwardness, etc.. </p>
      </div>
    </div>
      <div className="back_card_rotate front_card_rotate">
          <span>Wolverine</span>
      </div>
  </div>
</div>

This particular div will be repeated based on how many items are stored in the backend.

For rotating these divs upon click, here's my approach:

constructor() {
        super();
          this.state = {rotated: false};
          this.trait_select = this.trait_select.bind(this);
}
trait_select = (e) => {
          this.setState({rotated: !this.state.rotated});
}

My issue lies in the fact that with repeated CSS classes, every item rotates when clicked because they all share the same classes. How might I differentiate the clicked item from others?

Answer №1

It seems like a good idea to make each trait_box its own component and handle its own state:

class TraitBox extends Component {
   constructor(props) {
     super(props);
     this.state = { rotate: false }        
   }
   trait_select = (e) => {...}
   render() {
      return ( <div className="trait_box..." ></div> )
   }
}

// Then, you can import/use that component in a container
class ContainerApp extends Component {
   render() {
     return (
       <TraitBox />
       <TraitBox />
       <TraitBox />
     )
   }
}

Now, each TraitBox can manage its own state and styles.

By the way, there's no need for this line:

this.trait_select = this.trait_select.bind(this);

If trait_select is an arrow function, it should automatically bind "this".

Answer №2

Modify the boolean value by replacing it with an array and implement the use of e.target.name to determine the selected trait:

constructor() {
  super();
  this.state = { rotated_traits: [] };
  this.trait_select = this.trait_select.bind(this);
}

trait_select = (e) => {
  const rotated_traits = this.state.rotated_traits

  rotated_traits[e.target.name] = !this.state.rotated_traits[e.target.name]

  this.setState({ rotated_traits });
}

Also,

<div className="trait_box polaroid" name={trait.id} onClick={this.trait_select}>
  <div className="main_trait_card" style={{transform: this.state.rotated_traits[trait.id] ? 'rotateY(180deg)' : 'none' }}>
    ..
  </div>
</div>

In case you do not have a trait.id, you can utilize the index:

traits.map((trait, index) =>
  ...
)

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

Configuring routes for Angular4 router is a vital step in creating a

Issue: I am currently setting up routes for my application, aiming to structure the URL as https://localhost:4200/hero=id, where the 'id' will be dynamically selected. However, this setup is not functioning as expected. If I attempt to use a URL ...

Send PS3 through user agent for redirection

If a user is accessing the site using a PS3, I want them to be redirected to a different webpage Below is the code snippet I have been attempting to use: <script language=javascript> <!-- if ((navigator.userAgent.match(/iMozilla/i)) || (navigato ...

Turn off wss for ASP.NET Core Hot Reload functionality

Currently, I am utilizing ASP.NET Core's hot reload functionality. It attempts to establish connections with two websockets: ws and wss. The ws connection is successful and enables hot reload to function properly. However, since my local development ...

Is it feasible to implement different themes besides 'light' and 'dark' in React Material UI?

Currently, I am developing a user interface (UI) using React in combination with Material UI (v5+). The documentation provides information on how to utilize the extendTheme function along with CssVarsProvider to incorporate MUI colors into CSS. It also men ...

modifying the vertex color of a line in threejs based on individual vertices

I'm working on a project in three.js where I have a line passing through points of a particle cloud. Currently, I am using a canvas renderer and looking to add some randomness by varying the color of the line from vertex to vertex. I came across an ex ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

The callback functions, such as afterMove, are not being executed

This code snippet is copied from Owl Carousel's official website. I am having trouble getting the callback functions like afterMove to work. Can anyone help me figure out why the afterMove function is not being called? It seems that none of the callba ...

Leveraging the power of the return statement within an ES6 generator

I am curious about the implications of using a return statement instead of yield in a generator function. function *gen(){ const val = yield someAsyncFn(); assert.equal(val,4); return val; } How does the behavior of return differ from that of yield? ...

Resolving the issue: "Unable to destructure the 'Title' property of 'fac' as it is undefined" in React JS

I'm facing an issue with react-bootstrap mapping in my component whereby I encounter the following error: Cannot destructure property 'Title' of 'fac' as it is undefined. It seems like there's an error when trying to de ...

A guide on adding an onClick listener to a span element dynamically and then saving it to MongoDB

I have been attempting to add an onClick event within a span tag as shown below, with the goal of storing it in MongoDb. However, my event does not seem to be saving and is automatically removed. When I retrieve data from the database, it is not present. H ...

Discovering the dissimilarity between two nested arrays containing objects by comparing their OBJECTID values

Struggling to figure out how to filter a nested Object array based on the OBJECTID. I understand filtering arrays with strings/numbers, but this example is more relevant to what I am working on. let geojson = [ {properties: {OBJECTID: 6249646, FeatureCo ...

If I include beforeRouteEnter in one component, the this.$route property may become undefined in another component

I seem to be encountering an issue. After implementing a beforeRouteEnter method in one component, I am unable to access this.$route in another component. Here is the structure of my app: <div id="app"> <settings-modal></settings-modal ...

Tips for overlaying text on top of two images positioned side by side

I'm attempting to overlay text on two images placed side by side to fill the entire page. Here is the code: HTML: <div class="main"> <img src="city.jpg" class="city" alt="city"> ...

Setting button height dynamically in React Native

I've implemented a button using React Native Elements in my layout. Here's the code snippet: <Button title="Login" buttonStyle={{ backgroundColor: Colour.green }} containerStyle={{ ...

What is causing all Vuejs requests to fail in production with the error message "javascript enabled"?

My vuejs application interacts with a REST API in Node.js (Express, MongoDB Atlas). Everything runs smoothly when I run the Vue app on localhost while the Node.js app is on the server. However, when I deploy my dist folder to the server, although the app ...

Obtaining registration IDs for sending push notifications in curl PHP can be achieved by following these steps

Essentially... the scenario involves two working files: a curlphp script and an angular1 js file. In the js file, when an admin user clicks on 'send notification', it triggers an event to send a message by calling curl through a function. The f ...

Combine the initial element of one array with the initial element of another array in JavaScript

Is there a more efficient way to concatenate the first item of one array with the first item of another array in JavaScript, and automate console.log for each pair? Check out the code snippet below: $("button#search").on("click", function(){ var inputVa ...

What is the best way to create a clickable entity that is being dynamically generated in a networked A-Frame environment?

I'm attempting to use a networked A-frame to create a new entity upon page load. I want to incorporate various functionalities, such as hover and click events, on these entities. However, my attempts to make them clickable have been unsuccessful. f ...

Choose a file in React by specifying its path instead of manually picking a file

Is there a way for me to automatically select a file from a specified path into my state variable without having to open a select file dialog? I'm looking for a solution where I can bypass the manual selection process. Any suggestions on how this can ...

Save array data to a file in Node.js once it finishes looping

I've been struggling to find a solution to my issue despite looking at examples from other questions. I have created a basic web scraper in nodejs that stores data in an array and now I need help writing this data to a file. I'm having difficulty ...