Rob Cable Rob Cable - 4 months ago 23
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

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) {
    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')
);

And then what it looks like:

Example gif

Comments