How to get password field value in react's material-ui - javascript

I am not able to access the value of <TextField />, if i don't write <input type='password'/> then it works fine, but for this i am getting a TypeError, 'this.refs[this._getRef(...)].getInputNode is not a function'.
dialogAction(tag,e){
console.log(this.refs.password);
console.log(this.refs.password.getValue());
this.refs.dialog.dismiss();
}
render(){
let self = this;
let row = this.row,col = this.column;
let standardActions = [
{ text: 'Cancel',onTouchTap: this.dialogAction.bind(this,ProductConstants.CANCEL)},
{ text: 'Submit',onTouchTap: this.dialogAction.bind(this,ProductConstants.SUBMIT)}
];
return (
<div className="ProductRepository">
<Dialog ref = 'dialog'
title="Dialog With Standard Actions"
actions={standardActions}
actionFocus="submit"
modal={true}>
<TextField ref='password'
hintText="Password"
floatingLabelText="Password">
<input type="password" />
</TextField>
</Dialog>
</div>
);}
}
image below is the console output of the above code.

This solved my issue:
<TextField ref='password'
hintText="Password"
floatingLabelText="Password"
type="password">
</TextField>
After that
this.refs.password.getValue()
gives the desired output.
For React v >= 15.6
<TextField ref={x => this.password = x}
hintText="Password"
floatingLabelText="Password"
type="password">
</TextField>
in inputHandler function
this.password.value

For material 1.0 and react 16.1.1
Use inputRef
<TextField autoFocus={true} inputRef={el => this.fv = el}
placeholder="Required" size="30"></TextField >
To read the value use below line
console.log(this.fv.value);

Assign ref="password" to the input itself instead of the TextField. Currently you are executing getValue() on some abstract (probably some container) tag (TextField), not on the input itself.
Here's how it's done.

You can get the input value like this :
this.refs.password.input.value;

Related

React Hooks Form: undefined value on submit

I'm trying to create separate input component and use React Hook Forms, Here is component:
export default function TextInput({label, id, placeholder, name, ...params}) {
return (
<FormGroup>
<Label htmlFor={id}> {label} </Label>
<Input
className="form-control"
placeholder={placeholder}
name={name}
id={id}
{...params}
/>
</FormGroup>
);
}
and I'm calling it like this:
const {register, handleSubmit} = useForm();
const onSubmit = (data) => {
console.log(data);
}
<form onSubmit={handleSubmit(onSubmit)}>
<TextInput
label="input password"
placeholder="password"
name="password"
{...register("password")}
id="password"
type="password"
/>
<button type="submit">submit</button>
</form>
But when I click submit, password seems to be undefined
React-hook-version is 7.33, any ideas about what is the problem?
lets say you passed the a varible to get value from Input Field.
and next step will be to give this input field a function so that it can update the value of that variable in your case passowrd.
to do that I will use onChange.
<input onChange={(event)=>{resister.password = event.target.value}}/>
or
<input onChange={(event)=>{resister['password'] = event.target.value}}/>
and according to useForm documentation
you should be using resister in <input/> not in <TextInput/>
const { onChange, onBlur, name, ref } = register('firstName');
// include type check against field path with the name you have supplied.
<input
onChange={onChange} // assign onChange event
onBlur={onBlur} // assign onBlur event
name={name} // assign name prop
ref={ref} // assign ref prop
/>
// same as above
<input {...register('firstName')} />
https://react-hook-form.com/api/useform/register

How to get the TextField value with onclick button event React Material UI

I am trying to get the input value of a search TextField, then on the click of "Search" button, call the API with the search input. Here's what I have so far:
const handleSearchSubmit = async () => {
setSearchTerm(searchForm.current.value)
console.log(searchTerm)
const fetchSearch = async () => {
const params = {searchTerm: searchTerm}
console.log(params)
const response = await axios("/api/search", { params });
const data = response.data
setResTable(data)
console.log(resTable)
};
fetchSearch();
};
<TextField
id="searchInput"
inputRef={searchForm}
style={{ margin: 8 }}
placeholder="Enter a code or procedure"
fullWidth
/>
</FormGroup>
</Col>
<Button variant="contained" color="primary" onClick={handleSearchSubmit}>
Search
</Button>
I cannot seem to get the value of the TextField input. When I console.log it, I get an empty array. Any suggestions?
You need to use onChange in your TextField.
Create a state variable and set it in onChange.
<TextField
id="searchInput"
inputRef={searchForm}
onChange={(v) => setValue(v.target.value) } //Add your setVariable to this line
style={{ margin: 8 }}
placeholder="Enter a code or procedure"
fullWidth
>
Then use the variable to do your search.

TypeError: props.set is not a function

I'm extremely new to ReactJS and have been struggling quite a bit. Right now, I'm trying to create a setting in an admin page where the admin can enter text and update a section on the web app's home page. I created const [aboutBox, setAboutBox] = useState("") in Home.js and passed it as props to another file. However, every time I try to type anything in the text box on the admin page, it throws the error "TypeError: props.setAboutBox is not a function". I have used the same format to create other functions and those have worked, so I'm not exactly sure what's going wrong. Any help would be greatly appreciated!! Thank you guys so much!
const HomeAboutForm = (props) => {
const handleInputChange = event => {
console.log('handle input change')
const box = event.target;
props.setAboutBox({ ...props.aboutBox,box})
}
return (
<form>
<TextField
onSubmit = { event => {
event.preventDefault();
if (!props.aboutBox) return
const box = event.target;
props.setAboutBox({ ...props.aboutBox,box})
console.log(props.aboutBox)
}}
placeholder="Enter new text for About Section here"
multiline
value={props.aboutBox}
variant="outlined"
rows={4}
style={{ margin: "10px", width: '600px' }}
rowsMax={6}
required
input type="text" name="name" value={props.aboutBox} onChange={handleInputChange}
>
<input type="text" name="name" value={props.aboutBox} onChange={handleInputChange} />
</TextField>
<p></p>
<input type="submit" value="Submit" />
</form>
);
};
EDIT: The parent component to HomeAboutForm also has its own parent component, but the code calling HomeAboutForm is
<HomeAboutForm
aboutBox = {props.aboutBox}
setAboutBox = {props.setAboutBox}/>
There is however, a function called getChoiceView that is called like {getChoiceView(pageNum,props)} and then from there, the function has the code
const getChoiceView = (pageNum, props) => {
switch (pageNum) {
case 0:
return <AddPhoto />;
case 1:
return <HomeUpdateAboutView
aboutBox = {props.aboutBox}
setAboutBox = {props.setAboutBox}/>;
case 2:
return <HomeUpdateStylistForm />;
default:
return "Unknown pageView";
}
};
Could how I'm calling getChoiceView be the issue?

Sending parameter with function to child component and back to parent component

I've got a custom component called InputWithButton that looks like this:
const InputWithButton = ({ type = "text", id, label, isOptional, name, placeholder = "", value = "", showPasswordReset, error, isDisabled, buttonLabel, handleChange, handleBlur, handleClick }) => (
<StyledInput>
{label && <label htmlFor="id">{label}{isOptional && <span className="optional">optioneel</span>}</label>}
<div>
<input className={error ? 'error' : ''} type={type} id={id} name={name} value={value} placeholder={placeholder} disabled={isDisabled} onChange={handleChange} onBlur={handleBlur} autoComplete="off" autoCorrect="off" />
<Button type="button" label={buttonLabel} isDisabled={isDisabled} handleClick={() => handleClick(value)} />
</div>
{error && <Error>{Parser(error)}</Error>}
</StyledInput>
);
export default InputWithButton;
Button is another component and looks like this:
const Button = ({ type = "button", label, isLoading, isDisabled, style, handleClick }) => (
<StyledButton type={type} disabled={isDisabled} style={style} onClick={handleClick}>{label}</StyledButton>
);
export default Button;
I'm using the InputWithButton component in a parent component like this:
render() {
const { name } = this.state;
return (
<React.Fragment>
<InputWithButton label="Name" name="Name" buttonLabel="Search" value={name} handleChange={this.handleChange} handleClick={this.searchForName} />
</React.Fragment>
);
}
If the button is clicked, the searchForName function is called:
searchForName = value => {
console.log(value); //Input field value
}
This is working but I want to add another parameter to it but this time, a parameter that comes from the parent component
// handleClick={() => this.searchForName('person')}
<InputWithButton label="Name" name="Name" buttonLabel="Search" value={name} handleChange={this.handleChange} handleClick={() => this.searchForName('person')} />
The output in searchForName is now 'person' instead of the value.
I thought I could fix this with the following code:
searchForName = type => value => {
console.log(type); //Should be person
console.log(value); //Should be the value of the input field
}
However this approach doesn't execute the function anymore.
How can I fix this?
EDIT: Codepen
I would try handleClick={this.searchForName.bind(this, 'person')}, please let me know if it'll work for you.
EDIT:
I changed fragment from your codepen, it's working:
searchName(key, value) {
console.log(key);
console.log(value);
}
render() {
const { name } = this.state;
return (
<InputWithButton name="name" value={name} buttonLabel="Search" handleChange={this.handleChange} handleClick={this.searchName.bind(this, 'person')} />
)
}
as I suspected, just pass it an object and make sure you're accepting the argument in your handleClick function
handleClick={value => this.searchName({value, person: 'person'})}
or more verbose - without the syntactic sugar
handleClick={value => this.searchName({value: value, person: 'person'})}
then you can get at it with value.person
full codepen here
Hope this helps

Getting the input value for React Bootstrap FormControl

I have spent more than a day on what is probably going to be a very simple solution. I am using react-bootstrap.
I have a form that looks like this:
modal_form.js.jsx
...
render: function() {
var Modal = require('react-bootstrap').Modal;
var InputField = app.InputField
var formElementsCollection= this.props.formElements.map((formElement, i) => {
return (
<InputField
inputControlID="myInput"
inputLabel="Input Label"
placeholderText="My Placeholder"
key={i}
/>
)
});
return (
<Modal
keyboard={true}
show={this.props.showModal}
onHide={this.props.unloadModal}
>
<Modal.Header closeButton>
<h3>
{this.props.headerText}
</h3>
</Modal.Header>
<Modal.Body>
<form>
{formElementsCollection}
<button type="button" className="btn btn-info btn-fill pull-right" onClick={() => this.props.onClickHandler(this)}>{this.props.buttonText}</button>
</form>
<div className="clearfix"></div>
</Modal.Body>
</Modal>
);
}
...
input_field.js.jsx
...
handleChange(e) {
this.setState({ value: e.target.value });
},
render: function() {
var FormGroup = require('react-bootstrap').FormGroup;
var ControlLabel = require('react-bootstrap').ControlLabel;
var FormControl = require('react-bootstrap').FormControl;
return (
<FormGroup
controlId={this.props.inputControlID}
>
<ControlLabel>{this.props.inputLabel}</ControlLabel>
<FormControl
type="text"
value={this.state.value}
placeholder={this.props.placeholderText}
onChange={this.handleChange}
/>
<FormControl.Feedback />
</FormGroup>
);
}
...
As you can see, I am mapping out an array of values in my ModalForm parent and the creating an InputField child for each mapped value of the array. In the InputField child component, I then assign the value state of each element by making use of an 'onChange' method callback.
What I'm struggling to understand, is how to get the value of each of the InputField child components in my parent component? Since I'm using react-bootstrap and it's FormControl component, I do not have a 'ref' attribute to call. I'm not sure this is something that I need to explicitly define, but since the react-bootstrap docs don't provision for this attribute, I figured that there must be a better way of obtaining each value? Am I wrong in this assumption?

Categories