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;
}
Related
For normal html elements you can get the value of that element through a form.
function handleSubmit(event) {
event.preventDefault()
const formData = new FormData(e.target)
console.log(formData.get("test"))
// logs the value of the html element with the name "test"
}
<form onSubmit={handleSubmit}>
<input name="test" />
<button type="submit">Submit</button>
</form>
The form will assign a key "test" the value of whatever is inside the input on the form's submission.
My question: Is there a way to get this functionality to work with a Semantic UI Dropdown?
Below is ideally what I would think would work but I know doesn't because the component is a wrapper for other elements.
function handleSubmit(event) {
event.preventDefault()
const formData = new FormData(e.target)
console.log(formData.get("test"))
// logs the value of the html element with the name "test"
}
<form onSubmit={handleSubmit}>
<Dropdown name="test" selection options={
[{key: '1', text: 'text', value: '1'}]
}/>
<button type="submit">Submit</button>
</form>
On form submit, whatever value is selected in that dropdown is put into a key called "test" in formData. If no value is selected, an undefined value is given to the key "test."
Is this possible? I have another work around using a basic html selector but would like to not change a lot of already written code.
Yes, but you will need to deconstruct the dropdown component.
const [open, setOpen] = useState(false)
<Dropdown
trigger={<Button onClick={() => setOpen(true)}>Open</Button>}
onClose={() => setOpen(false)}
icon={null}
open={open}
simple
>
<Dropdown.Menu>
... add the options with the "name" tag ...
</Dropdown.Menu>
</Dropdown>
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>
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>
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) }
With the following method:
handleClick(event) {
const inputText = this.refs.inputText
console.log(inputText.value.trim())
}
I am trying to get Material-UI's <TextField/> to return the input text correctly with ref like the <input/> can with <button/> triggering it:
<input
className='form-control'
placeholder='Input Text'
ref='inputText'
type='text'
/>
<button
onClick={(event) => this.handleClick(event)}
>
And I attempted the following with <TextField/>, but it returns as undefined. How can I get it to return inputted text correctly like the <input/> above?
<TextField
hint='Enter text'
className='form-control'
ref='inputText'
type='text'
/>
I would suggest this approach:
Set up your textfield with a value and onChange function that are hooked into redux itself, where the onChange function just updates the value.
So you'd have something like this :
<TextField
value={this.props.textFieldValue}
onChange={this.props.textFieldChange}
Where the textFieldChange is an action that simply updates the textFieldValue. Most forms in redux will work something like this. Keep in mind the names i made up for those props and action are just for example. If you have a big form you might want to consider have part of the state tree dedicated to the form itself where you have :
state: {
form: {
textField: ...your textfield value here,
name: ...,
whateverElse: ...
}
};
I like doing this with redux because I can make that architect form part of the state to look like the json payload of wherever I'm sending it to, so there I can just send the form went I want to send it.
Anyways, back to this example. When you click your handleClick now. All you need to do is this to get the value:
handleClick(event) {
console.log(this.props.textFieldValue.trim());
}
Because the textfield is updated with every change, you always have access to it in your state. This also gives you flexibility over the refs approach, because if you use refs you will have a lot harder of a time getting access to that form in other components. With this approach, all the information is on your state so you can access it anytime, as long as you manage your props.
You should use the onChange={} to get the value:
_onChange = (e) => {
console.log(e.target.value);
}
<TextField
onChange={this._onChange}
/>
Here's a better solution than using onchange event, we get directly the value of the input created by material-ui textField :
create(e) {
e.preventDefault();
let name = this.refs.inputText.input.value;
alert(name);
}
constructor(){
super();
this.create = this.create.bind(this);
}
render() {
return (
<form>
<TextField ref="inputText" hintText="" floatingLabelText="Your name" /><br/>
<RaisedButton label="Create" onClick={this.create} primary={true} />
</form>
)}
hope this helps.