I'm trying to copy one form input value to another using state but the state isn't updating
I create a form, with a button, where the value from the left form input should be copied to the right form input. This is my code:
const ReviewContactForm = (props) => {
const contact = props.currentContact;
const dbContact = useDbContact(contact.Group);
const [dbSecName, setDbSecName] = useState("");
async function getDbContact() {
let secName = await dbContact.SecretaryName;
setDbSecName(secName);
}
getDbContact();
function acceptSecName(e) {
e.preventDefault();
setDbSecName(contact.SecretaryName);
}
return (
<>
<Form>
<Form.Row>Secretary's Name</Form.Row>
<Form.Row>
<Form.Group as={Col} className="mb-2">
<Form.Control type="input" name="1secname" value={contact.SecretaryName} readOnly />
</Form.Group>
<Form.Group as={Col} className="mb-2">
<Form.Control type="input" name="2secname" value={dbSecName || ""} readOnly />
</Form.Group>
<Button className="PrimaryButton" onClick={acceptSecName}>
Accept proposed
</Button>
<div className="divider" />
<Button className="SecondaryButton" size="sm">
Revert
</Button>
</Form.Row>
</Form>
</>
);
};
No matter what I do, the state of dbSecName doesn't change. I've tried setting a new const. I've tried making the onClick function async and await. If I add console.log for the value of the variable I'm trying to set to, I see it correctly, but the console.log of dbSecName always shows the original value.
I've not really an idea of what to do next. I'm thinking perhaps my approach to setting the form input in the first place is wrong.
So what I'm trying to achieve is that when the 'Accept proposed' button is clicked, the "2secname" form input is re-rendered with the value from "1secname".
Any help greatly appreciated
In the below code snippet
<Form.Control type="input" name="2secname" value={dbSecName || ""} readOnly />
replace value with just dbSecName instead of dbSecName || ""
See if that works
Related
I'm working with React and I'm trying to get a value entered by the user, but the value is returning empty, and for some reason the input is being filled, in a matter of one line of difference it's like the command .value did not work or exist
mudaTela = async () => {
var escolha = document.querySelector("#campo-tipo-relatorio");
console.log(escolha);
console.log(escolha.value);
}
when I run the above command the result is for the first console.log is as follows
<input aria-invalid="false" autocomplete="off" id="campo-tipo-relatorio" required="" type="text" class="MuiOutlinedInput-input MuiInputBase-input MuiInputBase-inputAdornedEnd MuiAutocomplete-input MuiAutocomplete-inputFocused css-1xqu1wk-MuiInputBase-input-MuiOutlinedInput-input" aria-autocomplete="list" autocapitalize="none" spellcheck="false" value="Detalhado">
however for the second console.log it is simply an empty field
and to do the input I'm doing it as follows
<Autocomplete
className="width-20"
id="campo-tipo-relatorio"
options={ret1}
getOptionLabel={(option) => option}
filterOptions={filterOptions}
onChange={this.mudaTela}
renderInput={(params) => <TextField {...params} label="Tipo de Relatório" required />}
/>
where the variable ret1 has two strings, with the text “Consolidado” and “Detalhado”
What I want to do is simple, just take input field values and do something with them by clicking button.
function TableFooterPanel() {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const sampleMethod = (x, y) => {
console.log(x + y)
}
return (
<>
<Card className='buttonFooter'>
<Form className='buttonFooter'>
<input type="text" placeholder="First Name" defaultValue={firstName} onClick={setFirstName}></input>
<input type="text" placeholder="Last Name" defaultValue={lastName} onClick={setLastName}></input>
<Button onClick={() => sampleMethod(firstName, lastName)}>Add</Button>
</Form>
</Card>
</>
);
}
export default TableFooterPanel;
Generally examples for that is done with separate handleChange() methods for each input field but I don't want to make separate functions for each so I though to use useState. How can I call the sampleMethod with these parameters ? I could not update values properly with useState.
if you use input field as text, you need onChange :
<input type="text" placeholder="First Name" defaultValue={firstName} onChange={e => setFirstName(e.target.value)}></input>
That way the text that you typing in the input will save in the state.
You can use FormData.
Another suggestion from me is to add an onSubmit event to the form. It's more convenient.
The button should be type="submit". When the user clicks on it the form's onSubmit event will fire.
I am finding it difficult to clear this file input that I am setting to setImportFile useState. This is the useState I declared
const [importFile, setImportFile] = React.useState<File | null>();
const [fileError, setFileError] = React.useState<string>("");
I clear two useState variables in this const method but only one gets cleared which is setFileError.
const clearModal = () => {
setImportFile(null);
setFileError("");
};
I use setImportFile in this method
const onChangeImportFile = (e: React.ChangeEvent<HTMLInputElement>) => {
e.preventDefault();
setImportFile(e.currentTarget.files ? e.currentTarget.files[0] : null);
setSaving(true);
};
This is my render in which I use the clear button and only the error would clear out but the file input will not clear out. I want to empty everything in the modal
<Form.Control
type="file"
accept='.csv, .xls, .xlsx'
required
className="primary mb-3"
name=""
onChange={onChangeImportFile}
/>
<Button variant="secondary" onClick={clearModal} > Clear </Button>
I think you need to pass the state value to the Form.Control, to make it controlled (otherwise it's not getting its value from the state).
<Form.Control
type="file"
accept='.csv, .xls, .xlsx'
required
className="primary mb-3"
name=""
value={importFile}
onChange={onChangeImportFile}
/>
You don't need to set File | null as SetStateAction will be set to undefined.
Try this:
const [importFile, setImportFile] = React.useState<File>();
setImportFile(undefined);
So I've tried the following, I can't seem to change the type of an input. So the same input can either be of type text or password but I can't switch between both. This is a Semantic UI Input. (from semantic-ui-react)
const [inputType, setInputType] = useState('password'||'text')
in my JSX:
<Input type={inputType} value={inputValue} onChange={handleInput} className="landingInput" placeholder={inputPlaceholder} />
at initialization:
setInputType('text');
after an event:
setInputType('password'); // should update html template with type="password" but it doesn't
useEffect is used to make sure state is updated, every other hook works as expected. Could this be a security precaution? Can you think of a way to avoid creating a new input?
Thank you
Toggling input type is easy,
Here I used a button to toggle the input type to text and password.
check the working demo Here.
Check the updated code block
const App=()=>{
const [inputType, setInputType] = useState('text');
const inputPlaceholder = 'Add Here';
const handleInput =()=>{}
const toggleInput = ()=>{
setInputType(inputType === 'password' ? 'text': 'password')
}
return (
<div>
<input type={inputType} value="password" onChange={handleInput} className="landingInput" placeholder={inputPlaceholder} />
<button onClick={toggleInput} >Toggle type</button>
</div>
);
}
I'm POSTing new product into my RESTful API and everything is being validated perfectly except doubles.
If I pass a double type for example '2.3' alert says that's incorrect and should be 2 or 3 instead.
const [isValidated, setIsValidated] = useState(false)
const handleSubmit = async event => {
const form = event.currentTarget
event.preventDefault()
if (form.checkValidity() === false) {
event.stopPropagation()
} else {
setIsValidated(true)
await ProductsApiService.postProduct(product)
props.onModalClose()
props.onRefreshList()
setIsValidated(false)
}
}
<Form onSubmit={handleSubmit} validated={isValidated}>
<Form.Group as={Col} controlId="productPrice">
<Form.Label>EUR</Form.Label>
<Form.Control
onChange={handleChange}
type="number"
name="eur"
placeholder="Price EUR"
required />
</Form.Group>
<Form.Row>
<Button variant="primary" type="submit">
Confirm
</Button>
</Form.Row>
</Form>
and this is working properly with '2.0' for example
You can use a pattern that Javascript validator API understands what type of number should deal with. so, for instance, the following pattern indicates the number input must start with a number and use either comma or a dot as a decimal character.
<Form.Control
onChange={handleChange}
type="number"
pattern="[0-9]+([,\.][0-9]+)?" // the Regex for having
name="eur"
placeholder="Price EUR"
required />
you can search for "decimal validation regex" to see all possible types of creating a pattern