Reputation: 29
The following code displays a list of images on a webpage using React JS:
this.searchResultsList = this.searchResults.map(function(photo){
return <div className="dataSetBox" key={photo.toString()}><img src={photo} alt="Image" height="350" width="450" margin="15px" border= "10" onClick={() => imageClick(id = "border")} /></div>;
})
When an image is clicked on the webpage, I want a border to appear around that image. would surround the image with a black border.
However, I want the border to only appear after the image has been clicked. My code above does not work and I get the error that id is not defined. Any idea how to fix it?
Upvotes: 0
Views: 1570
Reputation: 3443
Here is the sample of how you can manage this. You need a state variable to handle it. It will automatically toggle border on click.
const CSSVariables = {
border : {
border : '2px solid red'
},
noBorder : {
border : '2px solid transparent'
},
};
class TestJS extends React.Component {
constructor(props) {
super(props);
this.applyBorder = this.applyBorder.bind(this);
this.state = {
showBorder : false
}
}
applyBorder(){
this.setState(state => ({ showBorder: !state.showBorder }))
}
render() {
return(
<div id="root">
<img src="https://www.npmjs.com/static/images/avatars/Avatar2.svg" onClick={this.applyBorder} style={this.state.showBorder ? CSSVariables.border : CSSVariables.noBorder}/>
</div>
);
}
}
export default TestJS;
Upvotes: 4