ReactJS Calling method with onClick doesn't work fully - arrays

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>

Related

Svelte make {:then} value of {#await} statement reactive

I have to make an api call and then display the data (an array). I want to sort the array, but the displayed data is not updated. I suppose this is because my data is not a reactive variable? How can I make my each loop rerun when data changes?
My code (simplified):
{#await promise} // api call
<p>Loading</p>
{:then data}
<button on:click={() => data.sort()}>sort data</button> // does not work
{#each data as student}
<p>{student.firstname}</p>
{/each}
{/await}
data is a reactive variable. The presence of a promise is unrelated to the issue: this occurs even if data is a normal variable. The issue is that Svelte doesn't properly pick up that a change occurred to data when you click the button. You can force Svelte to pick up the changes by explictly assigning to data.
The other issue is that you can't sort objects without providing a custom sort function to sort based on a key of the object. .sort((a, b) => a.firstname.localeCompare(b.firstname)) sorts based on the firstname property of the objects.
Putting that together gives us:
<button on:click={() => data = data.sort((a, b) => a.firstname.localeCompare(b.firstname))}>sort data</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!

How to repeat an array n times using JSX

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.

I want to have a list of images to display randome, which is the best way?

I want to have a list of images that will be displayed in the background of a button randomly every time I click it.
Which is the best way to do it? I assume that not with an array since it has same size since it's initialized, and I think that I would like to reduced the list every time I click the button.
In js:
var array = ["https://madeby.google.com/static/images/google_g_logo.svg","http://searchengineland.com/figz/wp-content/seloads/2015/12/google-amp-fast-speed-travel-ss-1920.jpg"]
//whatever links you want
function go(){
var x = array[Math.floor(Math.random()*array.length)]
document.getElementById("hi").src=x
}
<button onclick="go()">start</button>
<img id="hi"></img>

Detect clicks on button array with a single method

Im working in a school project, a minesweeper. Will be 20x20, so it has 400 buttons. Its there a way to add an actionEvent/actionPerformed and implement a generalized method for the whole array? Or there is an easier way?
Maybe something like that (using jQuery for convenience but you can do it with Vanilla JS too):
Your HTML:
<div id="buttonsHolder">
<button data-num=1>1</button>
<button data-num=2>2</button>
<button data-num=3>3</button>
...
<button data-num=4>4</button>
</div>
Your JavaScript:
$('#buttonsHolder').on('click', 'button', (function(evt){
var buttonNum = $(this).attr('data-num');
// Now, buttonNum variable holds the button number has clicked.
});
Of course instead of use data-num atribute you can use whatever data you need.
You are placing the buttons inside a container (i suppose). Add a actionhandler to that to capture a click. And read the 'target' variable of the event, and see if that is a button

Resources