How can I add a bootstrap class in an onClick event.
How can I add a bootstrap class in an onClick event.
I want to change the class of my div when the image is clicked. I want to know if it is possible to do that with the onClick event?
imageSwitch = (image) =>
this.setState(
image: image
)
here is where the onClick is:
!items.media ? <div></div>
: items.media.length === 1 ?
<div></div>
: items.media.map((item, i) => <div className="col"
key=i>
<div className="card-nowna-outer" onClick=() =>
this.imageSwitch(item.url)>
<img className="card-img-top" src=item.url key=i alt="item.name"/>
</div>
</div>)
I want to change className="card-nowna-outer"
to className="shadow product-details-image"
when it is clicked. But also, my onClick()
already has something to do. What is the best approach to this?
className="card-nowna-outer"
className="shadow product-details-image"
onClick()
3 Answers
3
In here I use a schematic to your problem,
please note that I use a class in the component state and on click I update this class property.
class Component1 extends Component
constructor(props, context)
super(props, context);
this.state =
cssClass: 'card-nowna-outer',
image: ''
;
this.imageSwitch = this.imageSwitch.bind(this);
imageSwitch(image)
this.setState(
image: image,
cssClass: 'shadow product-details-image'
)
render()
return (
<div>
!items.media ? <div></div>
: items.media.length === 1 ?
<div></div>
: items.media.map((item, i) => <div className="col"
key=i>
<div className=this.state.cssClass onClick=() => this.imageSwitch(item.url)>
<img className="card-img-top" src=item.url key=i alt="item.name" />
</div>
</div>)
</div>
);
export default Component1;
Use element.classList.add()
Update your imageSwitch method as follows:
imageSwitch = (image) =>
// Assuming you have only one element with class as 'card-img-top'
var img = document.getElementsByClassName('card-img-top')[0];
if (img)
img.classList.remove("card-img-top");
img.classList.add("shadow");
img.classList.add("product-details-image");
this.setState(
image: image
)
You can use push() and join() to add class. push() method adds one or more elements to the end of an array and join() method joins all elements of an array into a string.
!items.media ? <div></div>
: items.media.length === 1 ?
<div></div>
: items.media.map((item, i) =>
<div className="col" key=i>
<div className=class_names.join('' ) onClick=() =>this.imageSwitch(item.url)>
<img className="card-img-top" src=item.url key=i alt="item.name"/>
</div>
</div>
)
let class_names = ["card-nowna-outer"];
imageSwitch = (image) =>
class_names.push("class_name");
this.setState( image: image )
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It is possible, toggle a variable onClick of the image and set it to the state. Then change the class according to the state variable. Simple
– Abinthaha
Aug 21 at 5:28