Rob Cable Rob Cable -5 years ago 157
CSS Question

REACT: Add highlighted border around selected image

I want a border around the picture when I select it. So if I have 6 pictures and choose 3, I would like to have highlighted borders around those images. Question is,How can I do this? EDIT: I am using React for this dilemma.

Answer Source

This depends on how you want to track state in your app.. here is an example which tracks the state in the parent component. Essentially you have a single parent App component which tracks the state for each image, and then an Image component which renders either with or without a border, depending on a piece of the App state which gets passed down as a prop. Refer to the code to see what I mean. An alternative would be to have the active state live within each Image component itself.

The code has a number of interesting features mainly due to leveraging several aspects of ES6 to be more concise, as well as React's immutability helper to help update the state array in an immutable way, and lodash's times method to assist in creating our initial state array.

Code (some of the indenting got a bit muddled in the copy from jsfiddle..):

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

class App extends React.Component {
  constructor(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: !}) }
    this.setState({ images });
  render() {
    const { images } = this.state;
    return (
        {, ix) =>
              clickImage={this.clickImage} />) }

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

  <App />,

And then what it looks like:

Example gif

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download