Updated - Not able to press backspace after programmatically changing Input Fields - javascript

I have an element as follows :
<SearchBar>
<InputText
type="search"
placeholder="Search for tasks in the BOQ..."
value={ taskName }
onChange={this.handleChangeInputTaskName}
/>
</SearchBar>
I want to keep the onChange method 'handleChangeInputTaskName' in place so the user can type in whatever he wants and I am able to process the input.
However, after processing the input from the user, I also want to be able to programmatically fill in the target value for the input field. Is it possible to achieve this?
=============================================================================
I was able to able to manually fill in the input field by just setting the state of the taskName to the desired value. However now it doesn't allow me to press backspace.

You can do this like this:
<SearchBar>
<InputText
type="search"
placeholder="Search for tasks in the BOQ..."
value={ taskName }
onChange={(value) => this.handleChangeInputTaskName('taskName ', value)}
/>
</SearchBar>

Use the component state to persist your value. This way it stays in sync as the user changes the value.
function showYourText(e) {
// Process
this.setState({ taskName : e.target.value })
}
<SearchBar>
<InputText
type="search"
placeholder="Search for tasks in the BOQ..."
value={ this.state.taskName }
onChange={(e) => showYourText(e)}
/>
</SearchBar>

Related

Why after onClick my hook is failing to update the state?

I have defined a constant to use UseState Hook in ReactJS by:
const [inputValue, setInputValue] = useState("")
Using the inputValue for my form in a way:
<form
data-testid="form"
onSubmit={e => {
e.preventDefault();
setLogFilters({
queryText: inputValue
});
}}
>
I am able to input string in my form using the snippet below:
<Input
name="input1"
type="text"
onChange={e => setInputValue(e.target.value)}
/>
I now have a button which onclick should clear the string input in the form:
<Button
onClick={() => {
setInputValue("");
}}
>
But the form retains the original string and the state is not set to null string. What is wrong? why is the hook not able to update the state?
As mention by #Corentin when you have any input field and you want its value to get change when you write something, you need to have a state for that, just like you have a state with name inputValue
you need to bind this state with your input through value prop i.e
<Input
//This will change your input when your state will be updated
value = {inputValue}
name="input1"
type="text"
onChange={e => setInputValue(e.target.value)}
/>
Now, the value will get change when you will set your inputValue state.
your input field does not have the value attribute, it should be like below:
<Input
name="input1"
type="text"
value={inputValue}
onChange={e => setInputValue(e.target.value)}
/>
For change the value of an input with hooks, you've to initialize your state like "value" in your input.
Example :
function onClick () {
setYourState('Blabla')
}
<input placeholder='Enter blabla' value={yourState} onChange={(e) => setYourState(e.target.value)}></input>

How to get a input value onChange in react variable?

I have a search text box I need to get the value onchange send the request to API when I use the normal event.target method it shows error. how to rectify it as in onchange I need to call a function with some arguments so I cannot go by ease.
my text box is :
<input className="ReactSearchBox" name="search" placeholder="Search Doctors"
onClick={() => {
this.onProviderListing(this.state.skip,0);
this.onEnable();
}}
onChange={() =>this.onSearchProvider(this.state.skip,0)} />
my function where i need the onchange value is:
onSearchProvider(nSkip,nLimit,e){
this.setState({
limit:nLimit,
skip:nSkip,
listing: this.state.listing,
searching: !this.state.searching
})
//console.log(nlimit);
var headers = {
"Content-Type":"application/json",
"AccessToken":localStorage.TOKEN,
}
var _calObj = {initiatorId:localStorage.userid,visitType: "office", skip:nSkip,limit:"5", includeOfflineProviders:"true",searchQuery:"lo"}
I need to give my input values in search query onchange correspondingly, sort it out plz.
You're not passing event from input. Change the onChange prop to:
<input className="ReactSearchBox" name="search"
placeholder="Search Doctors"
onClick={() => {
this.onProviderListing(this.state.skip,0);
this.onEnable();
}}
onChange={(e) =>this.onSearchProvider(this.state.skip,0, e)}
/>
onSearchProvider(nSkip,nLimit,e){
const value = e.target.value; // text box value
}
You can update the onChange in jsx by passing the e event object also like:
onChange={(e) => this.onSearchProvider(this.state.skip,0,e)}
and in onSearchProvider you can access it like:
onSearchProvider(nSkip, nLimit, {target}){
// you can see search box text here on change
console.log(target.value)
}
You don't need to pass state values on onChange method call.
State will be consistent throughout component.
<input className="ReactSearchBox" name="search" placeholder="Search Doctors"
onChange={() =>this.onSearchProvider(0)}
/>
And you can get value from event of that input as event.target.value
onSearchProvider(nLimit,e){
// access your state values directly here like this.state.skip
const searching = e.target.value;
}

How to add two value in react?

I am preparing a demo of add function where user enter two values in input field and result will be display on third field
But I am not able to show that result
Here is my code
https://codesandbox.io/s/flamboyant-smoke-ewkbd
return (
<div className="App">
Add Demo
<br />
<br />
<br />
{state.map(({ type, label, name }) => {
if (type === "text") {
return (
<div>
<label>{label}</label>
<input type="text" onChange={handleChange} name={name} />
</div>
);
}
})}
</div>
);
When I entered 2 in first field and 2 in second field .Expected output will be 4 in result field
I agree with your idea of using State, but better use form value where you can freely update your values.
If you need calculation, you can use number type rather than text
Use setForm for update value
Provide value with form values and show result with combination of first and second.
https://codesandbox.io/s/nice-violet-tv0vw

React - changing input value from a state

Alrighty, so I'm using some color picker that changes my this.state.colorPicked and that works fine, now I have an input field I'd like to write a function that I can call that would concat the value of my state colorPicked if it was empty, or concat comma and that value if it was not, how can I access this input field?
I'm using react-bootstrap
<InputGroup className="mb-3">
<FormControl
name="color"
onChange={this.change}
placeholder="Available Colors"
aria-label="Available Colors"
/>
</InputGroup>
<div style={{ display: "flex", "flex-direction": "row" }}>
<TwitterPicker
className="mb-3"
onChange={this.handleColorChange}
/>
<Button
style={{
background: this.state.colorPicked
}}
onClick={() => this.addColor(this.state.colorPicked)}
>
Add Color!
</Button>
</div>
TIA
Clarification: I want to pick the color, the onchange detector sets it to the state and hence the button's background, now on button click I want to add it's hex (the state) to the text field as text input, if input is not empty I would precede that with a comma.
With react forms we use 2 way binding from state, onChange and value attributes.
First add the value attribute and set it to state property for ex inputField.
<FormControl
name="color"
onChange={this.change}
placeholder="Available Colors"
aria-label="Available Colors"
value=={this.state.inputField}
/>
Now you can write a logic inside your change function.. something like
change = (e)=>{
this.setState({inputField:e.target.value}
// then copy array from state
let arrFromState = [...this.state.colorPicked]
let updatedArray = [...arrFromState, this.state.inputField]
// or use concat, push etc
this.setState({colorPicked:updatedArray})
}
I didn't understood the exact thing you wanted to do.
But thats the basic approach while working with react forms. Two way binding
To access input value you can use onChange method on your input, pass it an event and access it through event.target.value. It should look similar to this:
<input onChange={(event) => logInputValue(event)}
const logInputValue = ({ event: { target: { value } = {} } }) => { console.log(value) }

can't edit input with prop value

I have a string , in certain places I need to insert input tags with values. Everything displays fine , but I can't delete or edit values in input. What is wrong with that input?
editModalText() {
let modalMessage="Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back"
return (
<div>
{modalMessage
.split("/")
.map((text, idx) =>
text.includes("#") ? this.replaceCharacter(idx, text) : text,
)}
</div>
)
}
replaceCharacter(idx, text) {
let formattedText = text.replace(/#/g, " ")
return (
<input
key={idx}
value={formattedText}
onChange={e => this.setState({input:e.target.value})}
/>
)
}
replace value={formattedText} with defaultValue={formattedText}
this way input will be editable. it will show default value on first render and as you type you'll store that value in your state.
you can read more about controlled and uncontrolled components in the docs
I think you need to bind the input value and the state together. I am not sure how you're currently calling replaceCharacter but I would do something like this :
replaceCharacter(idx) {
return (
<input
key={idx}
value={this.state.input.replace(/#/g, " ")}
onChange={e => this.setState({input:e.target.value})}
/>
)
}
This way when you update your state with the onChange event the value of the state will be populated in the input.

Categories