score:10
Accepted answer
this can be achieved with a simple toggle handler:
const imagespath = {
minus: "https://images.vexels.com/media/users/3/131484/isolated/preview/a432fa4062ed3d68771db7c1d65ee885-minus-inside-circle-icon-by-vexels.png",
plus: "https://cdn3.iconfinder.com/data/icons/glypho-generic-icons/64/plus-big-512.png"
}
class app extends react.component {
state = {
open: true
}
toggleimage = () => {
this.setstate(state => ({ open: !state.open }))
}
getimagename = () => this.state.open ? 'plus' : 'minus'
render() {
const imagename = this.getimagename();
return (
<div>
<img style={{maxwidth: '50px'}} src={imagespath[imagename]} onclick={this.toggleimage} />
</div>
);
}
}
const rootelement = document.getelementbyid("root");
reactdom.render(<app />, rootelement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
edit
note that i passed a function parameter for setstate
because my new state depends on the old state. you can read more about it in the docs
score:-2
assuming this is inside the render function:
<div>
<img onclick={() => {this.setstate({clicked: true})}
src={'../../' + (this.state.clicked ? 'plus' : 'minus') + '.png'}} />
</div>
score:0
try this sample code on button click change the condition to render the img src:
import react from "react";
import "./styles.css";
import { card, cardimg, cardbody, button } from "reactstrap";
class app extends react.component {
constructor() {
super();
this.state = {
loginstate: true
};
}
render() {
let sessonstate;
let imgurl;
if (this.state.loginstate) {
sessonstate = "logged in";
imgurl = "https://picsum.photos/id/237/200/300";
} else {
imgurl = "https://picsum.photos/seed/picsum/200/300";
sessonstate = "logged out";
}
return (
<div>
<h1>session {sessonstate}!!</h1>
<br />
<div classname="container">
<div classname="row">
<div classname="col-md-4">
<card classname="shadow">
<cardimg top width="100%" src={imgurl} alt="card image cap" />
<cardbody>
<button
classname="shadow-sm btn "
onclick={() => {
this.setstate({
loginstate: false
});
console.log(`${imgurl}`);
}}
>
button
</button>
</cardbody>
</card>
</div>
</div>
</div>
</div>
);
}
}
export default app;
score:0
import react, { usestate } from 'react';
import './bulbs.css';
function bulb(){
const bulboff = require('../assets/bulboff.png');
const bulbon = require('../assets/bulbon.png');
const images = {bulboff,bulbon};
const [img, setimg] = usestate(false);
const imgchangehandler = () => {
if(!img) {
setimg(true);
}else{
setimg(false)
}
};
return(
<div>
<img src={!img ? bulboff : bulbon } alt='bulb-off' onclick={imgchangehandler}/>
</div>
)
}
export default bulb;
Source: stackoverflow.com
Related Query
- Change image on click - React
- How to change image on button click with React Hooks?
- I want the image to change when i click the button in class component React JS
- React - change image on click - refactoring
- Prevent image from rerendering at every state change - React
- How to change Cursor Icon upon button click on React
- how to change image src using props with styled component and react
- Change state on click then change again after delay and show message in React
- Syntax to change image source based on states and props in react
- randomly change the background color of a react app by a click
- React Native - make image size not change when keyboard is open?
- React Native ListView not re-rendering on state change by click
- React JS - Change color on click and put defaul color on all other ones
- Change image onClick in React Js
- React Hooks, Conditionally change state inside onClick function, updates on the next click
- Too many re-renders when trying to change array of components on click on React
- React Change Image Source on Scroll Event
- How to use Refs to change image src in React js
- how to change background color when I click the button using react hooks
- react change the class of list item on click
- Use a common function to handle change of the multiple array-based similar states on the user click in REACT
- change button icon on click react
- How to change div background on click in React js?
- React - Using Conditional Rendering with window.location.href to change Background image
- React state does not change after click
- Change background image on React component hover
- Change an element on mouse click on an image
- React - on click div text, change text from another div
- How to change image and background color every x seconds. React
- Dynamically change Image -> React component
More Query from same tag
- Why do my React App reload after fetching data?
- Why does my reactstrap Collapse not reflect my initial or changed state
- Material UI - Replicating the "required" text field error message
- Updating a specific field of object state in React
- How to set different states based on checked/unchecked inputs with pre-loaded data
- Yup validation schema object conditional validation
- Convert a Buffer Array into an image
- How to remove whitespace from outside of container
- Access 'scrollLeft' property in react
- React dynamically using sub-components with props
- How can I disable chunk(code splitting) with webpack4?
- Get the branch of collection without the sibling elements, searching by property
- Reactotron doesn't work with NextJS because of SSR
- How to access a certain mapped element in React?
- Why the state is still showing Promise while using redux? and how should I access the array inside the result?
- ReactJS children - filter out null values
- POST API response blocked by CORS policy - React and Django Rest Framwork
- How to get the file length for an file in react js
- How to use callback in DIspatch in redux?
- reactjs datagrid use html
- How to create button with function of draw polygons in Leaflet?
- How can I force a component update with non-component class objects?
- React.js: How to delete row from an ag grid?
- My react SPA navigation currently renders the page for about a second and then goes back to my Main page
- Problems related to a resizable component
- Dynamic form additions and deletions, data with new, UI is not new of antd with React
- Require in reactjs is throwing cannot find module
- can't I dispatch actions in sequence?
- Pass parameters to mapDispatchToProps()
- Is it possible to assign CSS class to a React component?