I'm new here and I have a question that I couldn't find answer to..
I am currently working on a website using ReactJS, and I want to have a button that fills itself whenever the user clicks on it. The button should have a total of 5 stages to it.
I am not asking for you to code it for me, but simply help me finding the best approach to this thing.
So what exactly am I asking? As you can see in this
It's a boxed element that whenever the user clicks on it (it can click on the whole element), the progress fills and it becomes something like this
So the first line is now marked. When the user presses on it again, the 2nd bar fills
Important - there will be text inside these bars that fills.
What have I done so far? I have been thinking of having 5 different images for every time the user presses on the element, but I was wondering if there might be a better approach to it (Like having the DIV background the image, and have sub-divs that fills up whenever the user presses... )
I hope I made myself clear, and thank you all for your time!
Here is a working example. You don't need an image for all of the different states. It is far more flexible to do this dynamically with HTML.
The key to this is keeping track of the number of times the button has been clicked. In this example it uses currentState to keep track of how many times it has been clicked.
const defaultStyle = {
width: 100,
padding: 5,
};
class MultiLevelButton extends React.Component {
constructor(props) {
super(props);
this.state = {
currentState: 0,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const { currentState } = this.state;
if (currentState < this.props.states.length) {
this.setState({
currentState: currentState + 1,
});
}
}
reset() {
this.setState({
currentState: 0,
});
}
render() {
const { currentState } = this.state;
const { states } = this.props;
return (
<button onClick={this.handleClick} style={{border: 'none', outline: 'none'}}>
{
states
.map((s, i) => {
const stateNumber = states.length - i;
const overrides = stateNumber <= currentState ? { backgroundColor: '#000', color: '#fff' } : {};
const style = {
...defaultStyle,
backgroundColor: s,
...overrides,
};
return <div style={{...style}}>{stateNumber}</div>
})
}
</button>
)
}
}
const buttonRef = React.createRef();
ReactDOM.render(
<div>
<MultiLevelButton ref={buttonRef} states={['#bbb', '#ccc', '#ddd', '#eee', '#fff']} />
<MultiLevelButton states={['#fcc', '#cfc', '#ccf']} />
<div>
<button onClick={() => buttonRef.current.reset()}>Reset</button>
</div>
</div>,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app" />
As you are using react. use create step/level as component and you will pass props of styles. you can map that component 5 times or n times depending upon requirement. The view you have shown no need images use css to achieve it.
change props of component when user click on it.
You can use state in order to keep the click count and change the button background on the basis of click count.
const colors = ["#dfddc7", "#f58b54", "#a34a28", "#211717"]; //color array
class App extends Component {
constructor(props) {
super(props);
this.state = {
index : 0
}
}
handleChange() { // function will be called whenever we click on button
let {index} = this.state;
if (index >= 5) {
return; // you don't want to change color after count 5
}
index++;
console.log(index);
this.setState({index})
}
render() {
const {index} = this.state;
return (
<div className="App">
<button style = {{background:colors[index]}} //we are setting dynamic color from array on the basis of index
onClick = {this.handleChange.bind(this)}> click to change images
</button>
</div>
);
}
}
You can place <div></div> inside a button with different background color instead of images.
In the following example, I hold the number of clicks in the state. By comparing this value with the index of the step, you can see if it needs to be green or transparent
const numberOfSteps = 5;
class App extends React.Component {
state = {
numberOfClicks: 0
};
handleClick = e => {
this.setState({
numberOfClicks: (this.state.numberOfClicks + 1) % (numberOfSteps + 1)
}); // Use module (%) to reset the counter after 5 clicks
};
render() {
const { numberOfClicks } = this.state;
const steps = Array(numberOfSteps)
.fill()
.map((v, i) => i)
.map((i, index) => {
const color = numberOfClicks >= index + 1 ? "limegreen" : "transparent";
return (
<div
style={{
backgroundColor: color,
height: "30px",
border: ".5px solid gray"
}}
>
Bar {index + 1}
</div>
);
});
return (
<button
className="button"
style={{ height: "200px", width: "200px", backgroundColor: "lightgreen" }}
onClick={this.handleClick}
>
{steps}
</button>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
The key concept is state. When you click your button you should set some state, and when you render the button you should render it based on the state.
Here's a simple example where I render a button which contains 5 div elements that are filled (by setting backgroundColor style property) based on the state.
class Example extends Component {
constructor(props) {
super(props);
this.state = {
buttonState: 0,
};
}
onClick = () => {
let buttonState = this.state.buttonState;
buttonState++;
if(buttonState > 4) buttonState = 0; // wrap around from 4 - 0
this.setState({buttonState: buttonState});
}
// render a button element with some text, and a background color based on whether filled is true/false
renderButtonElement(elementText, filled) {
const backgroundStyle = filled ? {backgroundColor: 'green'} : {backgroundColor: 'white'};
const textStyle = {color: 'grey'};
return(
<div style={[backgroundStyle, textStyle]}>
<div>{elementText}</div>
</div>
);
}
render() {
return(
<button
onClick={this.onClick}
>
{/* make a temporary array of 5 elements, map over them and render an element for each one */}
{Array(5).fill().map((_, i) => this.renderButtonElement(i + 1, i <= this.state.buttonState))}
</button>
);
}
}
Related
I'm creating a webpage slide show. I created a file called SlideshowData.js where I exported an array of objects with all image links and ids. So using react I mapped through the photos and added dots to them. I created the dots and each time the photos switch the dot changes color from gray to black to indicate that the current photo is active.
The problem occurs now that I keep trying to figure out how to make them clickable. So for example you would click on the first dot it would bring you to the first slide. I tried to do it with a "set.state" function and set the initial index to the "event.target.key" which I assigned slide.id but it doesn't work.
Thank you for your time. I attached the code below.
class Slideshow extends React.Component{
constructor(props){
super(props);
this.state = {
index: 0,
delay: 5000,
length: SlideshowData.length,
}
this.clickedDot = this.clickedDot.bind(this)
}
componentDidMount(){
document.addEventListener("onClick", this.clickedDot)
if(this.state.index === this.state.length -1){
setTimeout(()=> this.setState(()=>({
index: 0
})),this.state.delay)
}else{
setTimeout(()=> this.setState((state)=>({
index: state.index + 1,
})),this.state.delay)
}
}
componentDidUpdate(){
document.addEventListener("onClick", this.clickedDot)
if(this.state.index === this.state.length -1){
setTimeout(()=> this.setState(()=>({
index: 0
})),this.state.delay)
}else{
setTimeout(()=> this.setState((state)=>({
index: state.index + 1,
})),this.state.delay)
}
}
clickedDot(){
this.setState((slide) =>({
index: this.state.length
}))
console.log(this.state.index)
}
render(){
return(
<div className="slidesContainer">
<div className="SlideshowSlider" style={{ transform: `translate3d(${-this.state.index * 100}%, 0, 0)` }}>
{SlideshowData.map((slide,index) => (
<img className="slides" src={slide.image} key={index} alt="travel"/>
))}
</div>
<div className = "slideshowDots">
{SlideshowData.map((slide,idx) => (
<div onClick={this.clickedDot} key ={slide.id} className={`slideDot${slide.id === this.state.index ? " active" : ""}`} ></div>
))}
</div>
</div>
)
}
}
export default Slideshow
You can pass the index inside your onClick function on the dots such as this:
<div onClick={(idx) => this.clickedDot(idx)} key ={slide.id} className={`slideDot${slide.id === this.state.index ? " active" : ""}`} >
and then use the index to change the slide accordingly in your clickedDot function.
I have a function which creates 2 divs when changing the number of items correspondingly (say if we choose 5 TVs we will get 5 divs for choosing options). They serve to make a choice - only one of two possible options should be chosen for every TV, so when we click on one of them, it should change its border and background color.
Now I want to create a dynamic stylization for these divs: when we click on them, they should get a new class (tv-option-active) to change their styles.
For that purposes I used 2 arrays (classesLess and classesOver), and every time we click on one of divs we should remove a class if it's already applied to the opposite option and push the class to the target element - thus only one of options will have tv-option-active class.
But when I click on a div I do not get anything - when I open the document in the browser and inspect the elements, the elements do not even receive new class on click - however, when I console log the classes variable that should apply to an element, it is the way it should be - "less tv-option-active" or "over tv-option-active". I applied join method to remove the comma.
I checked the name of imported css file and it is ok so the problem is not there, also I applied some rules just to make sure the problem is not there and it worked when it's not dynamic (I mean no clicks are needed).
So my list of reasons causing that trouble seems to be not working.
I also tried to reorganize the code in order to not call a function in render return - putting mapping directly to render return, but this also didn't work.
Can anyone give me a hint why it is that?
Here is my code.
import React from 'react'
import { NavLink, withRouter } from 'react-router-dom'
import './TVMonting.css'
import PageTitle from '../../PageTitle/PageTitle'
class TVMontingRender extends React.Component {
state = {
tvData: {
tvs: 1,
under: 0,
over: 0,
},
}
render() {
let classesLess = ['less']
let classesOver = ['over']
const tvHandlers = {
tvs: {
decrease: () => {
if (this.state.tvData.tvs > 1) {
let tvData = {
...this.state.tvData,
}
tvData.tvs -= 1
this.setState({ tvData })
}
},
increase: () => {
if (this.state.tvData.tvs < 5) {
let tvData = {
...this.state.tvData,
}
tvData.tvs += 1
this.setState({ tvData })
}
},
},
}
const createDivs = () => {
const divsNumber = this.state.tvData.tvs
let divsArray = []
for (let i = 0; i < divsNumber; i++) {
divsArray.push(i)
}
return divsArray.map((i) => {
return (
<React.Fragment key={i}>
<div
className={classesLess.join(
' '
)}
onClick={() => {
const idx = classesOver.indexOf(
'tv-option-active'
)
if (idx !== -1) {
classesLess.splice(
idx,
1
)
}
classesLess.push(
'tv-option-active'
)
}}
>
Under 65
</div>
<div
className={classesOver.join(
' '
)}
onClick={() => {
const idx = classesLess.indexOf(
'tv-option-active'
)
if (idx !== -1) {
classesOver.splice(
idx,
1
)
}
classesOver.push(
'tv-option-active'
)
// classesOver.join(' ')
}}
>
Over 65
</div>
</React.Fragment>
)
})
}
return (
<div>
<button onClick={tvHandlers.tvs.decrease}>
-
</button>
{this.state.tvData.tvs === 1 ? (
<h1> {this.state.tvData.tvs} TV </h1>
) : (
<h1> {this.state.tvData.tvs} TVs </h1>
)}
<button onClick={tvHandlers.tvs.increase}>
+
</button>
{createDivs()}
</div>
)
}
}
export default withRouter(TVMontingRender)
CSS file is very simple - it just adds a border.
P.S. I know that with this architecture when I click on one of the divs all the divs will get tv-option-active class, but for now I just want to make sure that this architecture works - since I'm relatively new in React 🙂Thanks in advance!
Components won't have their lifecycle triggered if you are mutating a variable. You need a state for that purpose, which stores the handled data.
In your case you need some state to say which div has the active class, under or over. You can also abstract each rendered Tv to another Class component. This way you achieve independent elements that control their own class, rather than changing all others.
For that I created a Tv class, where I simplified some of the logic:
class Tv extends React.Component {
state = {
activeGroup: null
}
// this will update which group is active
changeActiveGroup = (activeGroup) => this.setState({activeGroup})
// activeClass will return 'tv-option-active' if that group is active
activeClass = (group) => (group === this.state.activeGroup ? 'tv-option-active' : '')
render () {
return (
<React.Fragment>
<div
className={`less ${ activeClass('under') }`}
onClick={() => changeActiveGroup('under')}
>
Under 65
</div>
<div
className={`over ${ activeClass('over') }`}
onClick={() => changeActiveGroup('over')}
>
Over 65
</div>
</React.Fragment>
)
}
}
Your TvMontingRender will be cleaner, also it's better to declare your methods at your class body rather than inside of render function:
class TVMontingRender extends React.Component {
state = {
tvData: {
tvs: 1,
under: 0,
over: 0,
}
}
decreaseTvs = () => {
if (this.state.tvData.tvs > 1) {
let tvData = {
...this.state.tvData,
}
tvData.tvs -= 1
this.setState({ tvData })
}
}
increaseTvs = () => {
if (this.state.tvData.tvs < 5) {
let tvData = {
...this.state.tvData,
}
tvData.tvs += 1
this.setState({ tvData })
}
}
createDivs = () => {
const divsNumber = this.state.tvData.tvs
let divsArray = []
for (let i = 0; i < divsNumber; i++) {
divsArray.push(i)
}
// it would be better that key would have an unique generated id (you could use uuid lib for that)
return divsArray.map((i) => <Tv key={i} />)
}
render() {
return (
<div>
<button onClick={this.decreaseTvs}>
-
</button>
{this.state.tvData.tvs === 1 ? (
<h1> {this.state.tvData.tvs} TV </h1>
) : (
<h1> {this.state.tvData.tvs} TVs </h1>
)}
<button onClick={this.increaseTvs}>
+
</button>
{this.createDivs()}
</div>
)
}
}
Note: I didn't change the key you are passing to Tv, but when handling an array that you manipulate somehow it's often better to pass an unique id identifier. There are some libs for that like uuid, nanoID.
When handling complex class logic, you may consider using libs like classnames, that would make your life easier.
So, I have 100 mapped buttons from array, something like that
{
buttons.map((button, index) =>
<StyledGameButton
key={index}
value={button}
onClick={this.checkButton}>
{ button < 10 ? `0${button}` : button }
</StyledGameButton>
)
}
I want user to click all the buttons from 0 to 99, so when he click for example 0 the button should change color. I made function checking if he clicked correct button, and if yes then I am addind data-attr to that button (thats how I am changing the color of buttons):
checkButton = e => {
const buttonId = e.currentTarget.getAttribute('value');
const nextButton = this.state.currentButton === null ? 0 : this.state.currentButton + 1;
if (buttonId == nextButton){
this.setState({
currentButton: parseInt(buttonId),
});
if (this.state.currentButton === 99) {
this.gameEnd();
};
e.currentTarget.setAttribute('data-status', 'correct');
}
}
The problem is that I want to make reset button, that will change all buttons to 'unclicked' so I have to delete data-attr from all buttons on one click. How can I do this? Or is there a better solution to manage 'state' of single button without making 100 states?
100 checkboxes demo
use an Array to store the state would be fine.
const list = [...Array(100).keys()].map(x => ({ id: x }));
const App = () => {
const [selected, setSelected] = React.useState([]); // init with empty list
const onChangeHandler = id => () => { // pass index/identify params
selected.includes(id) // check whether been checked
? setSelected(selected.filter(x => x !== id)) // yes, remove
: setSelected([...selected, id]); // no, add
};
const onRemove = () => {
setSelected([]); // remove all, set to empty list
};
return (
<div className="App">
{list.map(item => (
<input
type="checkbox"
key={item.id}
checked={selected.includes(item.id)}
onChange={onChangeHandler(item.id)}
/>
))}
<br />
<button onClick={onRemove}>Remove all</button>
<div>{selected.join(",")}</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
I'm creating a gameBoard, and having trouble toggling background colors for button divs. The toggle works for individual clicks on the "buttons" (styled divs), but when I click adjacent buttons it requires two clicks to get the next button to change its background color. How can I get adjacent buttons to toggle on first click? I've read some related posts like (Changing style of a button on click) but still struggling to get this working -
Related code below,
full code: https://jsfiddle.net/lydiademi/kt2qgfpr/
TY!
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
color: '#FFF',
color_white: true,
currentWord: '',
board1: [],
row1: ["aaafrs","aaeeee","aafirs","adennn","aeeeem"],
}
this.clicked = this.clicked.bind(this);
}
componentWillMount() {
let letter1 = '';
this.state.row1.forEach(die => {
letter1 = die[Math.floor(Math.random() * 6)].toUpperCase();
if (letter1 === 'Q') {
this.state.board1.push("Qu")
} else {
this.state.board1.push(letter1);
}
})
}
clicked(event) {
//change background color
let newColor= this.state.color === "#FFF" ? "#ACCEEC" : "#FFF";
this.setState({ color: newColor });
event.target.style.backgroundColor = newColor;
}
render () {
return (
<div id="board">
<div className="row">
{
this.state.board1.map((letter, index) => {
return (
<div className="btn" onClick={(e) => {this.clicked(e)}}>
{letter}
</div>
)
})}
</div>
)
}
Issue is :
You are maintaining one variable for all the elements bg toggle,
So the code is working as it should,
There is no need for maintaining state for that.
What you can do is :
Set extra attribute data-color like this
<div className="btn" data-color='#FFF' onClick={(e) => {this.clicked(e)}}>
And change bg color and attr based upon data-color , onClick like this
clicked(event) {
// get current color of element
let currentColor = event.target.attributes['data-color'].value;
// apply condition based upon currentColor
let newColor = currentColor === "#FFF" ? "#ACCEEC" : "#FFF";
// set the bg color
event.target.style.backgroundColor = newColor;
// change the data-color value to currentColor
event.target.setAttribute('data-color' , newColor);
// add letter to state.currentWord
let letter = event.target.innerText;
this.setState({ currentWord: this.state.currentWord + letter })
}
Here is the link to working fiddle :
https://jsfiddle.net/vivekdoshi2/kt2qgfpr/2/
So i have an array like this const divs = ["Text 1","Text 2","Text 3"].
I create divs (a small menu) from this array in my render function
var createThreeDivs = divs.map((category) => {
return <div key={category} onClick={this.handleClick} className="myDivClass">{category}</div>
});
I want to style one of these divs when i click on them, and the remove the styling on the rest of them. So when i select one of the divs it gets a color and removes the color on the rest of them
In normal javascript with no virtual DOM i could do like this:
handleClick(e) {
//remove styling from others
var allDivs = document.getElementsByClassName("myDivClass");
for(var i = 0; i < allDivslength; i++) {
allDivs[i].classList.remove("myDivClass-styled");
}
//Add styling class to selected,
e.target.classList.add("myDivClass-styled");
}
But this manipulate the DOM directly. How do i do something like this in React?
I have seen examples of how this can be done using state with only one element and by not having an array creating the divs. But i can't come up with a good solution for this scenario. Any suggestions?
Using the component's state you can update the color based on the active div. Update the index of the active div when the user clicks, and when the index equals the div that was clicked on update the color of that div.
See example below.
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
active: 0
};
}
render() {
const divs = ["Text 1", "Text 2", "Text 3"];
const updateActiveDiv = (value) => {
this.setState(() => {
//this line will reset the value to
//null if same element is clicked twice
if(value === this.state.active) {
value = null;
};
return {
active: value
}
});
};
let divText = divs.map((div, i) => {
let color = this.state.active === i ? 'red' : 'black';
return <div style={{ color }} onClick={() => updateActiveDiv(i)}>{div}</div>;
});
return (
<div>
{ divText }
</div>
);
}
}
ReactDOM.render(<Example />, document.getElementById('root'));
<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>
Pass current text from html
handleClick = (text)=>{
this.setState({activeText:text})
}
Inside create div function add class dynamically
Div className = { stat condition ? Class : no class }