REACT: Implement a feature to add a distinctive border around the currently selected image

When selecting a picture, I would like to have a border around it. Specifically, if out of 6 pictures I choose 3, I want highlighted borders around those selected images. How can this be achieved? EDIT: I am utilizing React to address this issue.

Answer №1

If you're wondering how to manage state in your app, there are a few different approaches you can take. One example is demonstrated here, where the state is tracked in the parent component. In this setup, the parent App component monitors the state for each image, while an Image component determines whether to display a border based on a specific piece of the App state passed down as a prop. Check out the code for more insight. Another option would be to have the active state stored within each individual Image component.

This code showcases several interesting features, such as the use of various ES6 functionalities for brevity, React's immutability helper for updating the state array in a immutable manner, and lodash's times method for creating the initial state array.

Here's the code snippet (note that some of the indentation may have been lost in copying from jsfiddle):

function getImage() {
    return { active: false };
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { images: _.times(6, getImage) };
    this.clickImage = this.clickImage.bind(this);
  }
  clickImage(ix) {
    const images = React.addons.update(this.state.images, {
      [ix]: { $apply: x => ({ active: !x.active}) }
    })
    this.setState({ images });
  }
  render() {
    const { images } = this.state;
    return (
        <div>
        { images.map((image, ix) =>
            <Image
              key={ix}
              ix={ix}
              active={image.active}
              clickImage={this.clickImage} />) }
        </div>
    );
  }
};

class Image extends React.Component {
    render() {
    const { ix, clickImage, active } = this.props;
    const style = active ? { border: '1px solid #021a40' } : {};
    return <img
              style={style}
              src={`https://robohash.org/${ix}`}
              onClick={() => clickImage(ix)}/>;
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);

Here's what the resulting interface looks like:

https://i.sstatic.net/bT12A.gif

Answer №2

To make an image selectable, you can add an event handler for the click event that toggles a "selected" class. Then, in your CSS, define the styles for the selected class to include a border.

.selectableImg {
  border: solid 1px transparent;
  margin: 10px;
}

.selectableImg.selected {
  border: solid 1px blue;
}
  
<img class="selectableImg"  src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
<img class="selectableImg" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
<img class="selectableImg" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
<img class="selectableImg" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>

<script>
  var images = document.querySelectorAll(".selectableImg");
  
  images.forEach(function(i) {i.addEventListener("click", function(event) {
    i.classList.toggle("selected");
    })});
  </script>

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

Even when applying a class, the CSS link:hover style will only affect the initial occurrence

I've hit a wall on this issue and can't seem to find a solution. I styled a few links using classes, but it seems that only the first link is accepting the :hover and :visited state styling. I made sure to use classes to style all of them. Not su ...

Ever since I switched to a different monitor, my Javascript has suddenly stopped functioning

I'm encountering an issue where my JS stops working every time I switch displays within a single HTML file. I've attempted to replace the HTML onclick call with a JavaScript function, but the problem persists. Update: Apologies for the unclear e ...

CKFinder Error: Unable to find definition for t.event.special.swipe

Upon using CKFinder 3.2.0 with Firefox 44.0, I encountered the following error message. Interestingly, this issue is exclusive to Firefox while Chrome works perfectly fine. Any insights on what could be causing this problem and how it can be resolved? Ty ...

Oops! Hardhat Test Error "Error: Virtual Machine Exception occurred while processing transaction: reverted with reason 'Please deposit additional funds'."

Encountering an issue with the following error message: Error: VM Exception while processing transaction: reverted with reason string 'deposit more' in the Hardhat Test.js file Test.js -> it("should be able to withdraw if no one appl ...

The end of the /if in the small template system fails to correctly detect the desired condition

If I write the following line on its own, he cuts it without any reason. So...: Greetings, I'm in need of assistance regarding an issue that is currently beyond my understanding. I'm facing a challenge with a small TPL-System which requires so ...

Understanding intricate JSON structures with JavaScript

Here is the JSON structure that I am working with: var data = [ { "country":"Andorra", "code":"AD", "state":[ { "state_code":"AD1", "state_description":"aaAndorra1" }, { " ...

I need help configuring headers for the graphql server when using renderToString from react-dom/server. Can anyone provide guidance on

My webserver is receiving the client's IP from the load balancer through the X-Forwarded-For header, but it is not being forwarded to the GraphQL server, causing some challenges in debugging. Do you think it's feasible to enable this feature or ...

Do I have to include 'document.ready()' for this JavaScript code snippet?

I am currently utilizing freemarker to dynamically generate HTML pages based on user requests. These pages contain a reference to a javascript file in the header section. Within this javascript file, there is an array that is defined. It is necessary for m ...

"Exploring the power of Node.js Virtual Machines and the magic of

I'm currently facing a challenge with reading and extracting data from a dynamically generated HTML file that contains a commented out JavaScript object. My goal is to retrieve this object as a string and execute it using VM's runInNewContext(). ...

Unpredictable order of replies retrieved using $http.get

I am struggling to create a function that sends multiple requests to the server based on the number of Ids in the idArray. The issue I am encountering is that the data being pushed into the dataArray does not align with the corresponding Ids of the idArr ...

Utilizing an external SCSS or CSS file with Material UI in React: A step-by-step guide

Encountering issues with external CSS files in my React project that uses Material UI components. Despite creating a CSS file for each component in the react components folder, they fail to load upon hard reloading the site. I prefer using external CSS ov ...

Using jQuery to create dynamic CSS effects directly on the drop-down menu button

Seeking your kind assistance once again... I am attempting to design a navigation bar that displays the dropdown section upon hovering over the buttons AND shows a bottom border on the button that was last hovered over My code functions properly when I ...

Show concealed elements above everything else

I've encountered an issue with my custom dropdown list as it displaces other elements when it appears. I want it to overlay on top of everything else, similar to the default select behavior. Despite trying to set position: relative; and z-index:100;, ...

How to set the default value of a select dropdown in PHP

I came across this snippet of code: <td> <select class="versionSelect"> <option value="5" <?php if($item->version === "5") echo "selected='selected'"; ?>>5</option> <option value="6" <?php ...

How can we reduce the size of a JSON object in Typescript before sending it to the client?

Currently, I am faced with a common challenge. I have a database object that is a standard JS object originating from a document database, and my goal is to transmit this object to the client. However, certain fields contain sensitive information that shou ...

Sending a POST request to a Flask server using Stripe and AJAX

I am attempting to implement a function that triggers an ajax request when a stripe form is submitted. However, using the .submit() method doesn't seem to be working as expected. Here is my current code: HTML <form action="/download_data" method= ...

Unveiling the Mystery: Why YUI-3 Grids & Google Chrome Cause Overlapping Texts

Although I'm not well-versed in UI design, I find myself having to work on some CSS for a side project. Currently, I am utilizing YUI-3 files such as grids, reset, and fonts, all version 3.9.1. The main issue I am encountering is that the text inside ...

The collapse button in Bootstrap 3.3 and jQuery 1.1 appears to be visible but unresponsive when clicked

This code isn't functioning properly as it displays the three horizontal bar button, but nothing happens when clicked. bootstrap-3.3 jquery-1.1 Toggle navigation CopyHere <div class="collap ...

Executing a cURL request using Node.js

Looking for assistance in converting the request below: curl -F <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a777f7e737b275a73777b7d7f34706a7d">[email protected]</a> <url> to an axios request if possible. ...

What is the best way to handle JSON data in vue.js?

I am facing an issue with vue.js. I want to create a settings page on the server program that has XML data. I believe it can be achieved by following these steps : server | parse XML to JSON client | get JSON and read JSON client | edit JSON client | ...