Skip to content

Instantly share code, notes, and snippets.

@Nicknyr
Created August 10, 2019 20:56
Show Gist options
  • Save Nicknyr/a9fb6ed82c7517e8b6cae049fb2626a2 to your computer and use it in GitHub Desktop.
Save Nicknyr/a9fb6ed82c7517e8b6cae049fb2626a2 to your computer and use it in GitHub Desktop.
React: Toggling elements onClick using state, an event handler, and conditional rendering
import React, { Component } from "react";
import styled, { css } from "styled-components";
const Styles = styled.div`
.red {
background: red;
height: 5em;
width: 5em;
display: inline-block;
margin: 1em;
}
.blue {
background: blue;
height: 5em;
width: 5em;
display: inline-block;
margin: 1em;
}
img {
display: block;
margin-left: auto;
margin-right: auto;
}
`;
class Main extends Component {
constructor(props) {
super(props);
this.state = {
waterImg: `https://thumbs.dreamstime.com/b/small-water-drop-splash-crown-14698311.jpg`,
fireImg: `http://d.stockcharts.com/img/articles/2017/09/15057727422401691285382.jpg`,
image: ""
};
}
handleClick = e => {
this.setState({
image: e.target.className
});
};
render() {
return (
<Styles>
<div className="red" onClick={this.handleClick} />
<div className="blue" onClick={this.handleClick} />
{
this.state.image === "blue" ?
<img src={this.state.waterImg} height="100" alt="water pic"/>
: ""
}
{
this.state.image === "red" ?
<img src={this.state.fireImg} height="100" alt="fire pic"/>
: ""
}
</Styles>
);
}
}
export default Main;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment