why state updates on second time clicking in react js - reactjs

I have a state which fills by name of empty form inputs. first time when you click on button it fills by some key but it is empty at all but in second time it fills by some key like "age" or other thing. Do anyone face with this kind of problem?

Check if this works:
<input value={age} onChange={(e)=>setAge(e.target.value)} />
or
setAge(()=>newValue);
if not, please share some code.

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>

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!

React - Select multiple checkboxes holding Shift key

I have a list of checkboxes in my React App. When I hold Shift key and click one - the others between current and the nearest checked one should become selected.
For now I'm tring to do somethimg like this:
<input onChange={(e)=>this.handleCheckbox(e)} value={id} checked={this.state.selected.IndexOf(id) > -1} type="checkbox" />
handleCheckbox(e){
if(e.shiftKey){
console.log("shiftKey is hold")
}
//here goes some logic to save checkboxes in the state
}
But the condition if(e.shiftKey) is never executed. What am I doing wrong?
For future visitors:
To check if the Shift key is pressed, check the e.nativeEvent.shiftKey in the click event.
You still have to implement the logic for actually checking the boxes. If you need help with that, let me know.
Hope this helps.
onChange is trigged after you let the key up. You should use the onKeyDown event.

Is there any way I can direct focus to a specific input field on a form?

I have a large form and I would like when the user clicks a "new" button for the focus to be placed in a specific input field. There's a grid on the form and every field has a known id. Note it might not be the first field so not easy to use the tab.
Would appreciate some advice if this is possible. Would save having to manually have the user move the cursor over and click in the input field.
Update: Changed "move cursor" to "change focus"
Here is one solution -
Angular js gives you an advantage of using some of the extra features so that you dont have to use the jquery.
Here is one way to implement the autofocus feature.
<div class="button" input-focus>{{element.idORname}}</div>
and the directive to be defined here.
.directive("inputfocus",function($timeout){
return {
link : function(element,attributes){
element.bind('click',function($timeout){
$timeout(function(){
element/*.parent() or.child()*/.find('type of the field you want to select')[0].focus();
);
);
);
Here you can use the javascript or jquery methods for the dom traversal if there are nested fields in your code.
$timeout is necessary to call for the focus after the browser renders when user has finished clicking the event
As you can see the find('')[0] is a replacement for find('').focus as the latter requires jquery to be used.
Place "autofocus" attribute on the element that you want to focus.
Example:
Name: <input type="text" name="name" autofocus />
If all the input ids are known, just use that.
$("#NewButton").on('click', function(){
//Other code.
$("#IdOfInputToBeFocused").focus();
});
Custom data attribute can be used with jQuery like this
<input data-field="special" />
And then that specific field can be called like this
jQuery('input').find("[data-field='special']").focus();

Submittable HTML5 Web Component

How do I create a form-submittable web component?
Background:
I have a customer-picker component that is basically a text input plus a tiny button to the right of the text box plus a dialog that pops up when the button is clicked. It is used in the same way as one might use an html select.
This component is used as part of an html form that is submitted in the old fashioned (non-ajax) kind of way. The actual html input is encapsulated privately inside of the customer-picker component.
Problem:
The text input's value is not submitted
I guess I can understand why this is. I suppose this is the desired behavior (otherwise we are breaking encapsulation).
So with all that said, how do I create a submittable web component?
For example, suppose I have a form like this:
<form action="action.jsp">
<input name="date-start"/>
<input name="date-end"/>
<input name="name-first"/>
<input name="name-last"/>
</form>
that gets submitted like this:
action.jsp?date-start=2016-06-01&date-end=2016-06-30&name-first=Joe&name-last=Smith
I would like to create the same form using components like this:
<form action="action.jsp">
<date-range name="date">
<full-name name="name">
</form>
that gets submitted exactly the same way as the example above:
action.jsp?date-start=2016-06-01&date-end=2016-06-30&name-first=Joe&name-last=Smith
I am aware of iron-form. But this solution has some problems.
For one, it does not emulate native form submission very well. In a normal html form, when you submit, the current page is automatically replaced by whatever is returned by the action URL. This doesn't seem to happen with iron-form.
Second. It only allows your component to contribute a single value to the submitted data. In the above mentioned date-range example, I would like two values to be submitted for one component.

Resources