Lightning Web Component setting dynamic style not working as expected - javascript

I'm currently trying to render a specific class across two lightning-badge components that is suppose to change both badges from inverse to success, but am getting this instead:
When the value on the left badge equals the value on the right (so in this case both are 3), they should both be green, otherwise they should both be grey. They should never be seperate colours.
The value on the left increases as the user saves a record and is checked on status of "Completed". For some reason only the class on the second badge is being updated with the new class that includes slds-theme_success. I may be missing something small, but just haven't been able to figure it out. Please see code below:
badgeClass = "slds-badge_inverse slds-var-m-horizontal_x-small slds-col";
get patientsCompleted() {
if(this.records) {
let completedArr = this.records.filter(value => value.fields.Status__c.value == "Completed");
if(completedArr.length === this.patientsTotal) {
this.badgeClass = "slds-badge_inverse slds-theme_success slds-var-m-horizontal_x-small slds-col";
}
return completedArr.length;
}
};
get patientsTotal(){
if(this.records) {
return this.records.length;
}
};
<span class="slds-col_bump-left">
<div class="slds-grid slds-gutters">
<lightning-badge class={badgeClass} label={patientsCompleted}></lightning-badge>
<div class="slds-col"> of </div>
<lightning-badge class={badgeClass} label={patientsTotal}></lightning-badge>
</div>
</span>

Have you tried moving badgeClass to a getter? Something like this:
get patientsCompleted() {
if(this.records) {
let completedArr = this.records.filter(value => value.fields.Status__c.value == "Completed");
// No longer needed
// if(completedArr.length === this.patientsTotal) {
// this.badgeClass = "slds-badge_inverse slds-theme_success slds-var-m-horizontal_x-small slds-col";
// }
return completedArr.length;
}
};
get patientsTotal(){
if(this.records) {
return this.records.length;
}
};
get badgeClass() {
let baseClass = "slds-badge_inverse slds-var-m-horizontal_x-small slds-col";
return this.patientsCompleted === this.patientsTotal ? `${baseClass} slds-theme_success` : `${baseClass}`
}
I suspect LWC field tracking has some precautionary mechanism and didn't trigger the update.
I am not sure but perhaps if 0 records are available you want the badges to remain gray? In that case include this.patientsTotal > 0 in the get badgeClass() {...}.
Happy coding.

Related

Changing a HTML element dynamically

I have a side drawer where I'm showing the current cart products selected by the user. Initially, I have a <p> tag saying the cart is empty. However, I want to remove it if the cart has items inside. I'm using an OOP approach to design this page. See below the class I'm working with.
I tried to use an if statement to condition the <p> tag but this seems the wrong approach. Anyone has a better way to do this. See screenshot of the cart in the UI and code below:
class SideCartDrawer {
cartProducts = [];
constructor() {
this.productInCartEl = document.getElementById('item-cart-template');
}
addToCart(product) {
const updatedProducts = [...this.cartProducts];
updatedProducts.push(product);
this.cartProducts = updatedProducts;
this.renderCart();
}
renderCart() {
const cartListHook = document.getElementById('cart-items-list');
let cartEl = null;
if (this.cartProducts.length === 0) {
cartEl = '<h2>You Cart is Empty</h2>';
} else {
const productInCartElTemplate = document.importNode(
this.productInCartEl.content,
true
);
cartEl = productInCartElTemplate.querySelector('.cart-item');
for (let productInCart of this.cartProducts) {
cartEl.querySelector('h3').textContent = productInCart.productName;
cartEl.querySelector('p').textContent = `£ ${productInCart.price}`;
cartEl.querySelector('span').textContent = 1;
}
}
cartListHook.append(cartEl);
}
}
By the way, the <p> should reappear if the cart is back to empty :) !
With how your code is setup, you would want to reset the list on each render. You would do this by totally clearing out #cart-items-list. Here is a deletion method from this question
while (cartListHook.firstChild) {
cartListHook.removeChild(cartListHook.lastChild);
}
But you could use any method to delete the children of an HTML Node. To reiterate, you would put this right after getting the element by its id.
P.S. You probably want to put more code into your for loop, because it seems like it will only create cart-item element even if there are multiple items in this.cartProducts.

How to re-factor this NativeScript simple image css swapper

I have a page that displays 3 images, and the user is expected to tap on one, then tap the Next button to continue.
So basically, I am simply adding some CSS to the image when it is tapped.
BUT... my code is ugly, and doesn't keep track of whether they ALREADY have one selected.
onPlanTap: function (args) {
const planImage = args.object;
const planImageSrc = planImage.src;
const planId = plan.id;
this.set("nextButtonOn", true);
var n = planImageSrc.search("off");
// Found, it is off - turn on
if (n > 0) {
var newOnSrc = planId + "-off.png";
planImage.src = newOnSrc;
this.set("currentPlan",planId);
FancyAlertService.showFancySuccess("Plan Secected!", "You have chosen the FREE plan.", "Ok");
}
else {
// It's already on, turn off
var newOnSrc = planId + "-on.png";
planImage.src = newOnSrc;
this.set("currentPlan","");
}
}
[ oh, the css I am adding, simply adds a thick white border to the image ]
I can't figure out how to only have one selected.
Is there some sort of "toggle" feature in NS I am missing, or would I have to write the logic myself? If that's the case, can anyone give me a nudge with some code?
Wrap your images inside some custom object.
class MyImage {
image;
isSelected:boolean;
}
Add data binding:
<ListView [items]="myDataItems" class="list-group">
<ng-template let-item="item" let-i="index">
<Image (tap)="selectImage(item)" class="item.isSelected ? styleA : styleB"></Image>
</ng-template>
</ListView>
And in your component file:
class MyComponent {
myDataItems: Array<MyImage>
selectImage(item: MyImage) {
//deselect all Items
//select this item
}
}

Conditional cell rendering in react-table

I have a column for buttons to toggle a modal. The problem is, I don't want to display the button for every single row. I only want to display the button on the first entry of the color.
Note that the colors are unpredictable (you don't know what colors will be displayed beforehand).
For example,
color toggler
black +
red +
red //don't display it here
yellow +
blue +
blue //don't display it here
blue //don't display it here
orange +
red +
black +
black //don't display it here
blue +
I have try to go through the document and some example, but I can't seem to find a solution to it (maybe something that I missed ?).
What I did was storing the first color in the state. Then I did with the theCheckFunc:
let flag = true
if (nextColor !== this.state.color)
this.setState({color: nextColor})
flag = false
return flag
Then in the columns I did.
Cell: props => (this.theCheckFunc(props) && <div onClick={somefunc}> + <div>)
However, everything seems to be frozen. The browser doesn't even respond.
Any good suggestion on how to do this ?
Don't use state with this, since you don't want to re-render based on new input. Instead, compute the array as part of the render.
For example, assuming that when you get to your render statement, you have a random array of colors like this:
['red', 'red', 'black', 'purple', 'purple']
Then this function could create the array you need with the data for render:
function getTableRowData(arr) {
let tableRowData = []
arr.forEach((color, n) => {
let toggler = true
if (n !== 0 && arr[n - 1] === color) {
toggler = false
}
tableRowData.push({ color, toggler, })
})
return tableRowData
}
Then you can iterate over the tableRowData in your render return and have it display the way you want to.
First set your color control variables in state or in class wherever you choose. In this example i'm choosing to control them over state.
constructor(props) {
super(props);
this.state = {
firstRedAlreadyHere: false,
firstBlueAlreadyHere: false,
firstGrayAlreadyHere:false,
....
...
}
}
then open a function to prepare a table. Later Use that function in render() to put table on component.
function putValuesToTable()
{
let table = [];
for (let i = 0; i < (YOUR_LENGTH); i++) {
{
let children = []; /* SUB CELLS */
/* IF RED COLOR IS NEVER CAME BEFORE, PUT A BUTTON NEAR IT */
if(!this.state.firstRedAlreadyHere)
children.push(<td>
<SomeHtmlItem></SomeHtmlItem></td> <td><button </button></td>)
/* ELSE DON'T PUT BUTTON AND CHANGE STATE. */
else
{
children.push(<SomeHtmlItem></SomeHtmlItem>);
this.state.firstRedAlreadyHere = true;
}
table.push(<tr>{children}</tr>);
}
}
return table;
}
I am changing state directly instead of this.setState(); because I don't want to trigger a refresh :). In render function, call putValuesToTable like this
render()
{
return (<div>
<table>
<tbody>
<tr>
<th>SomeParameter</th>
<th>SomeParameter2</th>
</tr>
{this.putValuesToTable}
</tbody>
</table>
</div>);
}
Use this example to extend your code according to your aim.

What is a more optimal way to change out an HTML element's.onClick element inside of a javascript function?

I'm playing around with a webapp using React. My code currently creates a list of buttons that can change the color of a circle, depending on the randomly-generated button the user clicks on. To enhance my code, when the user clicks the button, I want all of the buttons colors to change, and therefore need to update all of the button's onClick functions, since they pass their color as an argument to the function that changes the circle's color. Below is the solution I currently have: it requires me to remove every button, and then completely reconstruct the button. Just using button.onclick = function() { newOnclickFunction} does not work, and I have not been able to find the answer on my own. Any help would be greatly appreciated; I'm almost certain there's a better a way to do it than this.
let reflipPalleteCompletely = () => {
let everyButtonPossible = document.getElementsByClassName("colorChangeButton")
for( var button of everyButtonPossible){
button.style.backgroundColor = randomColor()
let myParent = button.parentElement
myParent.removeChild(button)
let freshButton = document.createElement("button", {value: "Click", className: "colorChangeButton", })
freshButton.innerHTML = 'Click'
freshButton.className = 'colorChangeButton'
freshButton.style.backgroundColor = randomColor()
let newOnclickFunction = () => { changeToNewColor(button.style.backgroundColor); reflipPalleteCompletely() }
freshButton.onclick = function() { newOnclickFunction() }
myParent.appendChild(freshButton)
The short answer is: if each button is supposed to change color to reflect the color value it represents, and that set of colors is re-randomized every time a button is pressed, then you can't and shouldn't avoid re-render of the buttons.
However, Mike is right: you're not using React properly if you're writing your own element-creation scripts.
Your component might look like this:
const buttonCount = 10
class Demo extends React.Component {
constructor(props) {
super(props)
this.state = {
currentColor: getRandomColor()
}
}
setColor = (newColor, event) => {
this.setState({
currentColor: newColor
})
}
render() {
let {
currentColor
} = this.props
let colorChoices = Array(buttonCount)
.fill()
.map(() => getRandomColor())
return (
<div className="Demo">
<div className="the-shape" style={{ backgroundColor: currentColor }} />
<ol className="color-choices">
{
colorChoices.map( color => (
<button key={ color }
style={{ backgroundColor: color }}
onClick={ this.setColor.bind(this, color) }
>
{ color }
</button>
))
}
</ol>
</div>
)
}
}
This all depends on you having a getRandomColor function that can generate a color. And it doesn't address making sure that the choices don't include the current color (although you could easily do that by e.g. generating 2n colors, filtering out the currentColor, then taking the first n, or somesuch).
If you really hate redrawing the buttons, you could save their refs and then have the setColor method iterate through them and modify their styles.
But the point of React is to avoid procedural mutation of the DOM in favor of declaring the desired DOM and letting the React engine figure out an efficient mutation strategy.
A direct answer to the question you asked: "what's a more optimal way to change out an HTML element's.onClick element?" might be: find a pattern that doesn't require you to change the function every time.
Instead of having this:
let newOnclickFunction = () => { changeToNewColor(button.style.backgroundColor); reflipPalleteCompletely() }
Try something like this instead:
function onClickButton(event) {
let button = event.target
let color = button.style.backgroundColor
changeToNewColor(color)
}
This way, the desired color value isn't baked into the onClick function. Instead, the function examines the button whose click invoked it, and uses its background as the argument to changeToNewColor.
With some clever CSS, you could write the desired color to a data- prop on each button, and have the browser do the work of calculating background-color from that. Then you could use event delegation on some ancestor element that contains all the buttons, that listens for a click on any element with that data- prop and does the same work as above. This way, you don't even have a click function on each button.

label inside combobox and conditional multiselect

I am building a pretty combobox with checkboxes and conditional entries. Everything works out alright, except for two features that I cannot figure out how to implement.
1) I would like to move the label inside the combobox, make it shift the values to the right, and appear in a slightly gray color.
2) I would like the value to ignore certain entries (group headers) selected. Those entries are there for functionality only - to select/unselect groups of other entries.
The entire project is in the zip file. You don't need a server, it's a client base app. Just download the archive, unpack, and launch app.html in your browser.
http://filesave.me/file/30586/project-zip.html
And here's a snapshot of what I would like to achieve.
Regarding your second issue, the best way I see is to override combobox onListSelectionChange to filter the values you don't want:
onListSelectionChange: function(list, selectedRecords) {
//Add the following line
selectedRecords = Ext.Array.filter(selectedRecords, function(rec){
return rec.data.parent!=0;
});
//Original code unchanged from here
var me = this,
isMulti = me.multiSelect,
hasRecords = selectedRecords.length > 0;
// Only react to selection if it is not called from setValue, and if our list is
// expanded (ignores changes to the selection model triggered elsewhere)
if (!me.ignoreSelection && me.isExpanded) {
if (!isMulti) {
Ext.defer(me.collapse, 1, me);
}
/*
* Only set the value here if we're in multi selection mode or we have
* a selection. Otherwise setValue will be called with an empty value
* which will cause the change event to fire twice.
*/
if (isMulti || hasRecords) {
me.setValue(selectedRecords, false);
}
if (hasRecords) {
me.fireEvent('select', me, selectedRecords);
}
me.inputEl.focus();
}
},
And change your onBoundlistItemClick to only select and deselect items in the boundlist not to setValue of the combo:
onBoundlistItemClick: function(dataview, record, item, index, e, eOpts) {
var chk = item.className.toString().indexOf('x-boundlist-selected') == -1;
if ( ! record.data.parent) {
var d = dataview.dataSource.data.items;
for (var i in d) {
var s = d[i].data;
if (s.parent == record.data.id) {
if (chk) { // select
dataview.getSelectionModel().select(d[i],true);
} else { // deselect
dataview.getSelectionModel().deselect(d[i]);
}
}
}
}
},
Regarding your first issue, it is easy to add the label using the displayTpl config option. But this will only add the text you need, without any style (grey color, etc). The combo is using a text input, which does not accept html tags. If you don't need the user to type text, than you may want to change the combo basic behavior and use another element instead of the text input.

Categories