Problems with React-Bootstrap button - button

This is what i'm trying to do https://react-bootstrap.github.io/components.html#btn-groups but when I click on one of the buttons I want another function to be called
<ButtonGroup>
<Button onClick = {this.onSubmit.bind(this,1)} key={1} active = {this.state.i == 1}>LEFT</Button>
<Button onClick = {this.onSubmit.bind(this,2)} key={2} active = {this.state.i == 2}>MIDDLE</Button>
<Button onClick = {this.onSubmit.bind(this,3)} key={3} active = {this.state.i == 3}>RIGHT</Button>
</ButtonGroup>
onSubmit(new_i: number) {
this.setState({
i: new_i
});
}
I want only one button to be active at a time, the one I click on.
The default value of i is 1. So when I start the program the LEFT button is active and the 2 others are not, which is what I want. But after I cannot click on the other buttons because the value is always 1. And finally my question is how can I change the value on I only the I click on a button.

I would suggest if you're trying to make a item active by changing it CSS or adding a CSS class showing it's active you do something like so, this is a basic example showing that a style is being applied to an element based on the state of i.
https://jsfiddle.net/chrshawkes/64eef3xm/
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
var Hello = React.createClass({
getInitialState: function () {
return { i: 1 }
},
onSubmit: function (value) {
this.setState({ i: value })
},
render: function() {
return (
<div>
<div onClick = {this.onSubmit.bind(this,1)} key={1} style = {this.state.i == 1 ? {color: "red"} : {color: "blue"}}>LEFT</div>
<div onClick = {this.onSubmit.bind(this,2)} key={2} style = {this.state.i == 2 ? {color: "red"} : {color: "blue"}}>MIDDLE</div>
<div onClick = {this.onSubmit.bind(this,3)} key={3} style = {this.state.i == 3 ? {color: "red"} : {color: "blue"}}>RIGHT</div>
</div>
)
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);

Related

React ignores one of two style classes

Two buttons are rendered in my button component. Depending on the label, the button receives the class addButton or clearButton.
Button Component:
import './Button.css'
interface ButtonProps {
lable: string,
disabled: boolean,
onClick: MouseEventHandler<HTMLButtonElement>
}
export const Button: FunctionComponent<ButtonProps> = ({ lable, disabled, onClick}): ReactElement => {
let style: string = lable == 'ADD' ? 'addButton' : 'clearButton';
console.log(lable);
console.log(style);
return(
<div>
<button className= {`button ${style}`} type='button' disabled= { disabled } onClick= { onClick }>
{lable}
</button>
</div>
);
}
In the stylesheet Button.css are the two classes addButton and clearButton. Strangely, only the style class that is in second place is loaded. In this situation, the addButton receives its colour and the clearButton remains colourless. If I place the style class of the clearButton in second place in the stylesheet, it receives its colour and the addButton remains colourless.
Button.css
.clearButton {
background-color: #8c00ff;
}
.addButton {
background-color: #7ce0ff;
}
If I outsource both style classes to separate stylesheets, it works but this is not an elegant solution.
I would also like to understand the problem
I've execute your code, and it works, I think the problem is where you call the button you are not passing props to
change import type of button style
import styles from './Button.css';
return(
<div>
<button className={`button ${label === 'ADD' ? styles.addButton : styles.clearButton}`}>
{lable}
</button>
</div>
);
and reolace background-color to background
.clearButton {
background: #8c00ff;
}
.addButton {
background: #7ce0ff;
}
you can test code in this codesandbox project

Add color on every button Click React js

Hello guys I currently have a buttons like category. I want that when I click a button it will have a color, and when I click it again it will turn to it's original color which is white. When I click 2 button both will have dark color, then click again to remove single color.
this is my div when I'm adding a the category id
<div className={classes.scrollMenu}>
{categories.map((category) => {
return (
<>
<Button
key={category._id}
className={classes.button}
onClick={(e) => {
let values = {
price: [],
category: [category._id],
}
}}
>
{category.name}
</Button>
</>
)
})}
</div>
This is the image that when I click single button it will color one button.
Thank you
code Solution: https://codesandbox.io/s/stoic-meadow-y5cei?file=/src/App.js
App.js
import "./styles.css";
import React, { useState } from "react";
export default function App() {
let categories = ["one", "two", "three"];
const [activeFilter, setActiveFilter] = useState(["one"]);
const categoryOnClick = (category) => {
activeFilter.includes(category)
? removeCategory(category)
: setCategory(category);
};
const setCategory = (category) => {
setActiveFilter([...activeFilter, category]);
};
const removeCategory = (category) => {
const index = activeFilter.findIndex((cat) => cat === category);
activeFilter.splice(index, 1);
setActiveFilter([...activeFilter]);
};
return (
<div className="chip-list my-3">
{categories.map((category, index) => {
return (
<button
key={index}
className={`${activeFilter.includes(category) ? "active" : ""}`}
onClick={() => categoryOnClick(category)}
>
<span>{category}</span>
</button>
);
})}
</div>
);
}
css
.active {
background-color: black;
color: white;
}
check if this solution works for you
used useState hook to hold the state of buttons which you will select
.active class will apply to the button which is selected
On click of that button we will check if the button is already selected or not if selected removeCategory() function run
or if button is not selected then setCategory() function will run and it will update the state
if you need clarification please let me know thanks
Few tips to start with:
Fragment is unnecessary when wrapping single DOM element
Inline function initialisation inside a render is a bad thing. On each new re-render, it allocates extra client memory to newly initialised function. That means, for every map object you will have that many functions, that gets newly created and referenced on each reload
You can easily go with single line return statement of arrow function here. () => <hi> instead of () => { return <hi> }
As for solutions, there are quite a few ways to change button colour during execution. I will suggest the most simple (in my opinion) way to do it. Just have classname variable, then add subclass that will style button accordingly.
Example:
By default it has class name of .button, after click you simply add styling and it ends up having .button .button--red, all is left to do, declaration in css.
.button {
style button here
. . .
add additional stylings here
. . .
&.button--red { color: red }
}
As for how handler should look like, if that is what you asking. Button could be used in your new component let's say, named StyledButton or ColourfulButton that will have internal state to handle what kind of colour is represented.

Removing a class from "untoggled" items and assigning it to selected item in React

I made a toggle component (Accordion to be exact)
I am mapping through an array of objects and listing them like:
{object.map((o) => (
<Accordion key={o.id} title={o.question} className="item">
<div className="text"> { o.answer } <div/>
</Accordion>
))}
It renders something like this:
> Question 1
> Question 2
> Question 3
Now, every time I click a question, it toggles down to show the answer. All this works fine(I used hooks).
I want to be able to change the opacity of all the un toggled elements in this list when ONE of the questions is opened.
So if I open question 2, it becomes the "current item" and the opacity of question 2 and its answer should be 100% and all others(question1 an question3) should dim out or turn 50% opacity.. I am able to do it using :hover using css but that only works on hover.
Basically in theory, I should be able to select an item and remove the base class from all other items except the selected one. I don't know how to do that in reality. Help.
I feel like I'm missing something obvious.
const Accordion = ({ title, children, opened = false }) => {
const [show, setShow] = useState(opened);
const rotation = classnames('icon', {
'rotate': show,
});
const content = classnames('contents', {
'closed': !show,
});
useEffect(() => {
setShow(opened);
}, [opened]);
const toggle = useCallback(() => {
setShow(!show);
}, [show]);
return (
<div className='titleContainer' onClick={toggle}>
<div className={rotations}>
<i className='icon' />
</div>
<h5 className='title'>{title}</h5>
</div>
<div className={content}>{children}</div>
);
};
I finally understand what you mean, I think this is the answer:
const questionColor = (questionIndex, activeQuestion) => {
if (activeQuestion !== null && activeQuestion !== questionIndex) {
return "rgba(0,0,0,0.1)";
} else return "rgba(0,0,0,1)";
};
Working solution here:
https://codesandbox.io/s/cocky-hellman-fxrmc

How to change Cursor Icon upon button click on React

How do I change my cursor to be an icon when I click a button and then place that icon down on the second click, and become a regular cursor again? I'm working in React. All I have is that when I button is clicked, the global boolean clicked is turned to true.
Is this useful for what you need?
const [cursor, setCursor] = useState('crosshair');
const changeCursor = () => {
setCursor(prevState => {
if(prevState === 'crosshair'){
return 'pointer';
}
return 'crosshair';
});
}
return (
<div className="App" style={{ cursor: cursor }}>
<h2>Click to change mouse cursor</h2>
<input type="button" value="Change cursor"
onClick={changeCursor}
style={{ cursor: cursor }}
/>
</div>
);

How to change button icon when button is clicked in react.js

I have a react function which returns a button.
<div className="col-6 btn-group btn-group w-100">
<AuditMenuButtons buttonValue='Pending' buttonName='Inbox' changeFilterForButton={this.props.changeFilterForButton} icon={icon_inbox}/>
<AuditMenuButtons buttonValue='Rejected' buttonName='Rejected' changeFilterForButton={this.props.changeFilterForButton} icon={icon_rejected}/>
<AuditMenuButtons buttonValue='Accepted' buttonName='Accepted' changeFilterForButton={this.props.changeFilterForButton} icon={icon_accepted}/>
</div>
Function is added below
function AuditMenuButtons(props) {
return(
<button className="w-25 btn menu-btn p-lg-3" name={props.buttonName} value={props.buttonValue} onClick={props.changeFilterForButton}><img src={props.icon} className="pr-3 menu-btn-icons">
</img>{props.buttonName}</button>
);
}
You will see 3 buttons in above code. I want to change the button icon when one button is clicked. actually button icon color should be green when button is clicked. Images are .png file (with green and silver border). I tried button:active in css it didn't work for me. Image should remain until I clicked another button or page was refreshed
In this case, the icon part is a UI state, it has to maintained in your state and passed down to AuditMenuButtons has props.
use these props in AuditMenuButtons to do the desired check.
import React,{Component} from 'react';
class demoComponent extends from Component{
this.state={
isClicked:false,
buttonIcons:{
pending:{active_Icon:"../IconURL",Icon:"../IconURL"},
rejected:{active_Icon:"../IconURL",Icon:"../IconURL"},
accepted:{active_Icon:"../IconURL",Icon:"../IconURL"}
}
}
clickHandler = (event) =>{
this.setState(
{
isClicked:!this.state.isClicked // this is gonna toggle everytime you click //
}
);
}
render(){
return <div className="col-6 btn-group btn-group w-100">
<AuditMenuButtons clickhandler={this.clickHandler} buttonValue='Pending' buttonName='Inbox' isClicked={this.state.isClicked} buttonIcons={this.state.buttonIcons} changeFilterForButton={this.props.changeFilterForButton} icon={icon_inbox}/>
<AuditMenuButtons clickhandler={this.clickHandler} buttonValue='Rejected' buttonName='Rejected' isClicked={this.state.isClicked} buttonIcons={this.state.buttonIcons} changeFilterForButton={this.props.changeFilterForButton} icon={icon_rejected}/>
<AuditMenuButtons clickhandler={this.clickHandler} buttonValue='Accepted' buttonName='Accepted' isClicked={this.state.isClicked} buttonIcons={this.state.buttonIcons} changeFilterForButton={this.props.changeFilterForButton} icon={icon_accepted}/>
</div>
}
}
export default demoComponent;
You can try something like this in your .css file.
.button:focus{background: url('your new green image');
You can manage the image path in react state and call a method attach
it to onClick, where you use setState() and update the state.
Refer
https://reactjs.org/docs/handling-events.html
https://reactjs.org/docs/react-component.html#setstate
this.state = {
image_path: 'your image url here'
}
changeUrl = () => {
this.setState({image_path:'new path'});
}
<AuditMenuButtons onClick={this.changeUrl} src={this.state.image_path}/>
You can try with this:
changeFilterForButton: function (props) {
props.currentTarget.style.backgroundColor = '#ccc';
}
function AuditMenuButtons(props) {
return(
<button className="w-25 btn menu-btn p-lg-3" name={this.props.buttonName}
value={this.props.buttonValue} onClick={this.props.changeFilterForButton}><img src={this.props.icon} className="pr-3 menu-btn-icons">
</img>{this.props.buttonName}</button>
);
}
or if you want to use react methodology then you can use construtor like this
constructor(props) {
super(props);
this.state = {isColor: false};
// This binding is necessary to make `this` work in the callback
this.changeFilterForButton= this.changeFilterForButton.bind(this);
}
changeFilterForButton() {
this.setState(state => ({
isColor: !state.isColor
}));
}
function AuditMenuButtons(props) {
return (
<button className="w-25 btn menu-btn p-lg-3" name={props.buttonName} value={props.buttonValue} onClick={props.changeFilterForButton} style="background-color: {this.state.isColor? '#CCC' : ''} "><img src={props.icon} className="pr-3 menu-btn-icons">
</img>{props.buttonName}</button>
);
}

Resources