React. Conditional Button text not working - reactjs

I have this Button react-bootstrap component
<Button
className="btn-omega has-icon"
onClick={() => { handleFavsClick(data.products)}}
variant=""
>
<Icon size="1.75rem" />
{ liked ? 'Remove from Bookmarks' : 'Add to Bookmarks' }
</Button>
The problem is that text inside conditional if sometimes works and sometimes not
The error message is:
Failed to execute 'insertBefore' on 'Node'
The Icon works fine all the time
const Icon = liked ? BsBookmarkDash : BsFillBookmarkCheckFill
The variable liked is defined here
const key = `like-${id}`
const [liked, setLiked] = useLocalStorage(key, false)
basically is true or false

Is working this way (with a span html tag):
<Button
className="btn-omega has-icon"
onClick={() => { handleFavsClick(data.products)}}
variant=""
>
<Icon size="1.75rem" />
<span>
{ liked ? 'Remove from Bookmarks' : 'Add to Bookmarks' }
</span>
</Button>

Related

Highlight clicked button with React/Tailwind

I want to change the appearence of an button after clicking it.
I have tried adding focus: / active:, but react is re-rendering the component on-click, so it doesn't work.
In Javascript I would add an event-handler to every button that would automatically change the appearence after being clicked, how am I able to recreate that in react/tailwind-css, since tailwind is not working with dynamic className changes?
Is there a good practice, or should I add if statements in order to make it work?
This is what I am trying to recreate.
HTML:
<button>MY BUTTON</button>
<button>MY BUTTON</button>
<button>MY BUTTON</button>
JS:
let button_list = document.querySelectorAll("button");
button_list.forEach(element=>{
element.addEventListener("click",function(){
button_list.forEach(remove_background=>{
remove_background.style.background="white";
});
this.style.background="black";
});
});
I would recommend a state variable to store the active button. Here's a simple example:
const ButtonList = () => {
const [activeButtonIndex, setActiveButtonIndex] = useState(0);
return (
<>
<button
className={activeButtonIndex === 0 ? "bg-white" : "bg-black"}
onClick={() => setActiveButtonIndex(0)}
>
My Button
</button>
<button
className={activeButtonIndex === 1 ? "bg-white" : "bg-black"}
onClick={() => setActiveButtonIndex(1)}
>
My Button
</button>
<button
className={activeButtonIndex === 2 ? "bg-white" : "bg-black"}
onClick={() => setActiveButtonIndex(2)}
>
My Button
</button>
</>
);
};

Changing material UI button text based on a condition

I am using the material UI button for my component and want to change the button text based on a condition that if order amount is 0, show button text as "cancel" else show "refund". Please help me how can I do the same.
<Button
className={classes.refundButton}
onClick={() => setIsDialogOpen(true)}
>
Refund
</Button>
You can use ternary operator for solution.
<Button
className={classes.refundButton}
onClick={() => setIsDialogOpen(true)}
>
{amount === 0 ? 'Cancel' : 'Refund'}
</Button>
You can just store the state and read from there conditionally...
import { useState } from "react"
const [amount, setAmount] = useState(0)
<Button
className={classes.refundButton}
onClick={() => setIsDialogOpen(true)}
>
{amount === 0 ? 'Cancel' : 'Refund'}
</Button>

How to change value of a button Typescript / React

I have a button with which I handle my language switcher, it is set up to handle cookie, url changes and now I need to make it to change my translations on page as well. The <img> tag is used for changing the country flag.
<button
onClick={() => {
const locale =
router.locale === 'en-us'? 'da-dk': 'en-us';
setCookie(locale);
{handleOnclick;}
router.push(/${locale}`,
`/${locale}`,
{
locale: false,
}); }} >
{router.locale === 'en-us' ? (
<img src={
menuItems.data.body[5].items[0].image
.url}/> ) : (
<img
src={
menuItems.data.body[4].items[0].image
.url
}/>)}
</button>
The function of switching between languages handleOnClick is working just fine (tested) This is an example:
<button value="da" onClick={handleOnclick}>
Danish
</button>
<button value="en" onClick={handleOnclick}>
English
</button>
But now I need to change the value onClick, since I am having only one button instead of 2, but I don't know how to exactly do it
You can declare a state and switch its value based on the previous value it had.
const [language, setLanguage] = useState('en');
// if your project is written in typescript you can use below line of code
// const [language, setLanguage] = useState<'en' | 'da'>('en');
const handleOnclick = () => {
setLanguage(prevState => (prevState === 'en' ? 'da' : 'en'));
// it can also be written like this
// setLanguage(language === 'en' ? 'da' : 'en');
// But the 1st is more robust when the event happens more frequently.
};
Then write the button like this
<button value={language} onClick={handleOnclick}>
{language === 'en' ? 'English' : 'Danish'}
</button>

Is this the correct way to change a Firestore document with a button next to it?

This is a portion of the code to a react.js chat app. 'Lumens' are upvotes. Every message generates a new document which is sorted by its createdAt time. This all works.
I am attempting to print a button next to each 'message' document that adds 1 to its 'lumen' field. This code is no longer giving me errors- except the entire app fails to load. What am I doing wrong? I will post the rest of my code if desired.
function giveLumen(p){
const db = firebase.firestore;
const messages = db.collection('messages').doc(this)
messages.update({lumens: 100})
}
function ChatMessage(props) {
const { text, uid, photoURL, lumens } = props.message;
const messageClass = uid === auth.currentUser.uid ? 'sent' : 'received';
return (<>
<div className={`message ${messageClass}`}>
<img src={photoURL || 'https://api.adorable.io/avatars/23/abott#adorable.png'} />
<div className = "lumens">
<button onClick= {giveLumen()} className="lumens">
💡
</button>
</div>
<p>{lumens}</p>
<p>{text}</p>
</div>
</>)
}
Thanks for any help.
When you're passing giveLumen() with parenthesis you're calling the function
<button onClick= {giveLumen()} className="lumens">
In the first time, I think you should remove them. So that you'll pass the reference to you're function
<button onClick= {giveLumen} className="lumens">
// You can also write it as following (almost the same)
<button onClick= {() => giveLumen()} className="lumens">

ReactJS buttons change color on click

I have 3 buttons in reactjs created with Material UI Buttons.
<>
<Button variant="contained">Button 1</Button>
<Button variant="contained">Button 2</Button>
<Button variant="contained">Button3</Button>
</>
How can I make that when clicking on one, it changes it's color (let's say blue) and the other ones reset to Default?
Because React use JSX, you can put javascript in your html component.
We can imagine a single state that manage your buttons.
in your component you create a state containing integer
const [buttonSelected, setButtonselected] = useState(0);
I'm using the react hook syntax, but it also depend on you implementation.
buttonSelected is the current value of the state and setButtonselected is the function that change the state. When you call it, React will rerender your component and change the display .
You can now add a click function on your return
...
<Button variant="contained" onClick={() => setButtonSelected(1)}>Button 1</Button>
<Button variant="contained" onClick={() => setButtonSelected(2)} >Button 2</Button>
<Button variant="contained" onClick={() => setButtonSelected(3)}>Button3 </Button>
...
This will change the value of buttonSelected each time you click a button.
We now need to change the color , for that we will use use makeStyle, but there is other way to do so.
First, create a style element outside of your component.
const useStyles = makeStyles((theme: Theme) =>
createStyles({
selected: {
background: 'blue',
},
default:{
background: 'default',
}
}
),
);
Then call it in your component
const classes = useStyles();
And finally you can set the style that you want depending on the value
...
<Button className={(buttonSelected === 1) ? classes.selected : classes.default} variant.....
<Button className={(buttonSelected === 2) ? classes.selected : classes.default} variant.....
<Button className={(buttonSelected === 3) ? classes.selected : classes.default} variant.....
...
This is a ternary operator, it's the equivalent of
if(buttonSelected === 1){
return classes.selected
} else {
return classes.default
}
And it should work.
You can learn about it in the conditional rendering of react and in the the styling in react
Dont hesitate if you got any questions :)

Resources