I have a v-for loop where a button is created for each iteration. I'm trying to make a toggle handler where clicking the button will toggle the color of the button. But since the buttons are dynamically created, all of their colors are changing ....
<div class="pets" v-for="pet in pets" :key="pet.id">
<button class="favorite" v-on:click="toggle">
<i v-bind:class="[{ 'red' : favorited }, 'material-icons']">favorite</i>
</button>
</div>
The pets array is being filled with a http call. My script looks like this:
<script>
export default {
name: 'home',
data() {
return {
pets: [],
favorited: false
}
},
methods: {
toggle: function() {
this.favorited = !this.favorited;
}
},
}
The Style tag just changes the color
<style scoped>
.red {
color: red;
}
Essentially, I'm trying to created a favorite button where you can toggle favoriting an object from the array pets. I know why my method would activate all my buttons. Since favorited is not unique to a button and coming from the data. So when favorited = true, the class 'red' is bound to all my buttons. My question is how do I bind the class 'red' to just the button I click on? I'm relatively new to Vue and this is driving me nuts lol! Someone please tell me how I can fix this.
Add a favorited property to your pet objects in the pets array. Then use that property.
<div class="pets" v-for="pet in pets" :key="pet.id">
<button class="favorite" v-on:click="pet.favorited = !pet.favorited">
<i v-bind:class="[{ 'red' : pet.favorited }, 'material-icons']">favorite</i>
</button>
</div>
Example.
If you didn't want to modify the pet object, then here is an alternate way.
Related
I have this VueJS component that displays a star-shaped button
<template >
<div id="tenseFav">
<button>
<img :src="imgForFavButton">
</button>
</div>
</template>
The computed property imgForFavButton returns a different image depending on if the item is in the list of favorites or not.
computed: {
imgForFavButton() {
const isFav = this.favs.has(this.id);
return isFav ? starOn : starOff;
},
},
I want to add animation on hover, so the image is the one with the yellow star and maybe some transition effects. I am not sure if I have to do this on CSS or VueJS.
On VueJS, I have no event to control the hover natively so I have to use something like:
<template>
<div id="tenseFav">
<button #click="emisor">
<img
#mouseover="hover = true"
#mouseleave="hover = false"
:src="imgForFavButton">
</button>
</div>
</template>
and then in the computed property use an if:
computed: {
imgForFavButton() {
if (this.hover === true) {
return starOn;
}
const isFav = this.favs.has(this.id);
return isFav ? starOn : starOff;
},
},
This works but it looks a bit hacky.
Is there a better way in 2022 for this kind of thing?
I feel that I will face a lot of problems trying to add a transition effect to this.
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
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.
I am currently designing a table that was made with rc-table. I made the last row for actions which renders the buttons edit and delete. I want to edit it's style with Sass but I was unable to
I also specified classes for both the edit and delete button since they'll have different background-colors.
Is it possible to access it directly via a class? or is there another way which I don't know about.
for example if you have something like this in your code
this.columns = [
{
title: 'Operations', dataIndex: '', key: 'd', render: (text, record) =>
<a className="delete-btn" onClick={e => this.onDelete(record.key, e)} href="#">Delete</a>,
},
];
you can add class t the a element and the overwrite those styles with your CSS/SASS.
like this
.rc-table td {
background-color: 'red';
// custom styles here
}
notice the className attribute in a.
I am trying to add a class to an element depending on whether the user has clicked on a link. There is a similar question here but it is not working as I wanted it to be.
I created a component which has its own internal data object which has the property, isShownNavigation: false. So when a user clicks on the a I change isShownNavigation: true and expect my css class isClicked to be added. Alas that is not happening - isShownNavigation stays false in the component when I displayed it {{isShownNavigation}} but I can see in the console that my method is working when clicked.
I imported my header component to the App. Code is below.
Header Component
<template>
<header class="header">
<a
href="#"
v-bind:class="{isClicked: isShowNavigation}"
v-on:click="showNavigation">
Click
</a>
</header>
</template>
<script>
export default {
name: 'header-component',
methods: {
showNavigation: () => {
this.isShowNavigation = !this.isShowNavigation
}
},
data: () => {
return {
isShowNavigation: false
}
}
}
</script>
Application
<template>
<div id="app">
<header-component></header-component>
</div>
</template>
<script>
import HeaderComponent from './components/Header.vue'
export default {
name: 'app',
components: {
'header-component': HeaderComponent
}
}
</script>
I am using the pwa template from https://github.com/vuejs-templates/pwa.
Thanks.
Don't use fat arrow functions to define your methods, data, computed, etc. When you do, this will not be bound to the Vue. Try
export default {
name: 'header-component',
methods: {
showNavigation(){
this.isShowNavigation = !this.isShowNavigation
}
},
data(){
return {
isShowNavigation: false
}
}
}
See VueJS: why is “this” undefined? In this case, you could also really just get rid of the showNavigation method and set that value directly in your template if you wanted to.
<a
href="#"
v-bind:class="{isClicked: isShowNavigation}"
v-on:click="isShowNavigation = true">
Click
</a>
Finally, if/when you end up with more than one link in your header, you will want to have a clicked property associated with each link, or an active link property instead of one global clicked property.