How to repeat an array n times using JSX - reactjs

I am using React/JSX in my app.
i need to reapet data from API n times in first time. if i click on button it reapet more n times. another click-> another n times reapet and over and over.
the api give me 1 results every time. i can define results if it necessary
my code:
const n=2;
arr:[];
handleClick(){
//i need the code to increase n another 2 times
}
//the array here without the code to fill api data. not relevant
this.state.arr.map((d,key)=>
<span>age: {d.age} </span>
<button onClick={this.handleClick} >
Expected result in first results:
age:20
age:24
after click on button:
age:20
age:24
age:48
age:19

Depends on where your API call is, but in order to update the array, you should be using this.setState in your handleClick
handleClick() {
this.setState({
arr: this.state.arr.concat(newContentArray)
})
}
No clue how your obtaining the data, but that's the general principle. Take your existing this.state.arr and concat the array with the new data.
Be sure to use bind or an arrow function on your button event handler.

Related

react component not updated after state update

I have an grid composed of lines. Each line has :
a number input filled by the user (amountWithoutTaxe)
a number label that should be automatically calculated after the previous one has been filled (amountWithTaxe) and that equals to thrice the previous one.
What I expect :
The user increases or decreases the first field and automatically the second one is updated.
Example : I put 2, then 6 is automatically displayed.
What I get :
The user increases or decreases the first field, the second one is only updated after he clicks on "add a line".
Example : I put 2, nothing is updated, I click on "add a line", then the field is updated.
This is the playground https://codesandbox.io/s/react-tsx-playground-forked-bss6sh?file=/src/index.tsx
I dont understand why its not working as expected, as the state is refreshed after the first input changes
It seems you are trying to do some changes on the state itself without the setLines function. If you change the attributes of lines that way, React does not know it needs to render, it needs to get a new array. The fix for this can be that in your onChange function you make a new variable called let newLines = [...lines] for example and do changes on it, then set newLines.
For your input element please consider the following change
<input
type="number"
value={line.amountWithoutTaxe}
onChange={(event) => {
let newLines = [...lines];
newLines[index].amountWithoutTaxe = event.target.valueAsNumber;
newLines[index].amountWithTaxe =
newLines[index].amountWithoutTaxe * 3;
setLines(newLines);
}}
></input>

Is there any alternative to each() for this scenario

So I have a list of buttons on my webpage and I have to iterate through the list of those buttons and based on the inner text value I have to click the matching button. Now the number of buttons are dynamic, so sometimes it can be 5 or sometimes it can be 6 or something else. Now I have written a code with each() and this works perfectly -
cy.get('buton').each(($ele) => {
if ($ele.text().trim() === "insurance") {
cy.wrap($ele).click()
}
})
My question is are there any other way this logic can be written(without using each).
You can select the button directly
cy.contains('button', 'insurance').click()
You can use filter() in combination with contains() to get your desired button and click it.
cy.get('button')
.filter(':contains("insurance")')
.click()

ReactJS Calling method with onClick doesn't work fully

so i'm making a sorting visualization in ReactJS.
I have a method called "bubbleSort" that will follow bubble sort algorithm to sort array.
I have an array generated and visualized on the screen called "array".
Now when i use
<button onClick={bubbleSort(array)}>Click here to sort</button>
It will Sort the array and change the visualized array automatically everytime the page loads. It's not what i want, i want it to sort the array and change the visualization when i click the button.
So i made another method like this
function doSort() {
bubbleSort(array);
console.log(array);
}
and call the button like this <button onClick={doSort}>Click here to sort</button>, it will sort the array, but the visualized array on the screen stay the same (random) and is not display correctly (sorted). I'm stuck and don't know what to do. Thank you very much for your time to help me.
welcome to StackOverflow, I think you should call the function using the pattern below.
<button onClick={() => bubbleSort(array)}>Click here to sort</button>

How to get value from a dropdown to a button?

I'm using react JS and I have a problem. I don't know how to get the value from my dropdown and put that value into a onclick button. I have read lots of topics but I haven't find anything really useful for a beginner like me.
I am using "scheduler" that helped me built my dropdown and some other stuffs.
So, my dropdown get data from a local file and looks like this:
{values.map(v => (
<option value={this.value}>{v.value}</option>
))}
console.log(ref)
And my button is like this:
<Button onClick={() => this.decrement()}>
Ajouetr la réservation
</Button>
The decrement method was only there to test if it was working, and it is.
Actually, what I want to do is quite simple: I have some values in my dropdown (from 1 to 7). And I have a state that says there is 30 places available. What I want is when I choose a specified item in my dropdown AND validate with my button and then my state to decrement with the specified number. Because right now it only decrement with 1.
I hope it's clear enough for someone to help me, because I spent 2 days on that problem and I don't know what to do.
Thank you :)
Next time, it's nice to provide an interactive example with your question. Here's a CodeSandbox I made that (I hope) illustrates your example (link). If you want to fiddle with the example, just click "Fork" in the top right corner.
Back to the solution:
I think what you're missing is storing the selected value in your state along with the 30 "places". What you want is to make your <select /> tag into a "controlled component". When someone interacts with the <select /> you want to change the internal state so that it matches the selected value. That way, when you call decrement() from your button, you can use the internal state's value rather than getting it from a ref (I think that's what you were trying to do).
Here's a link to the React doc that explains how to use forms, specifically the <select /> tag: (link).
Take care!
I would say that you can think about this in 2 different steps:
SET THE QUANTITY STATE
Set the state with the current dropdown value - For achieving this, you can just use the onChange method in your select:
<select name="quantity"
value={this.state.quantity}
onChange={this.onSelectQuantity}
>
In your constructor, you create a variable quantity inside your state
Create a function called onSelectQuantity where you will set the quantity state with setState.
Do not forget to bind the function onSelectQuantity on the constructor.
With this, every time that you change the value on select, your state would capture its value. You can log it from the function if you want to test if it works.
DECREMENT FROM THE BUTTON
After this, you can just decrease the value of the state again from decrement function
<Button onClick={this.decrement}>
Ajouetr la réservation
</Button>
You will have a function...
decrement() {
const newQuantity = this.state.quantity - 1;
this.setState({
quantity: newQuantity
})
}
Hope it helps!

counting no of array element an array

ineed to get the number of elements created at every instance when a button is click
<a class="item-content ng-binding" ng-href="#/lead/details/0/quotation/view/0/" target="_self" href="#/lead/details/0/quotation/view/0/">
2015-10-22 - 1000674
</a>
every time i click on a button a new element is been created with a serial number i need to find out the count of elements after every button clicks
i used
var quotationNumber = element.all(by.css('.item-content.ng-binding'));
it('should display Correct Quotation number in Lead Page',function(){
expect(quotationNumber.getText()).count();
});
my terminal sends an error message TypeError: expect(...).count is not a function. i need the size of that array elements. could some one help me to fix this issue
When you use element.all the returned promise has method count the getText called on element.all(selector).getText() returns an array of text so for that you can use length
var quotationNumber = element.all(by.css('.item-content.ng-binding'));
it('should display Correct Quotation number in Lead Page',function(){
expect(quotationNumber.count()).toBe(3);
});
Have you tried changing expect(quotationNumber.getText()).count(); to expect(quotationNumber.getText().count()); ?

Resources