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);
Related
im having trouble to get my UseState to show itself once i click a button, currently i have a function, that that use usestate and show my value on the screen, for example, when i write "miki" in the input box, it will show "miki" on the screen, however, it happens when i click the input box, and i want it to happen when im pressing the button, this is my code untill now:
import react, { useState } from "react";
export const ShoppingListPageContainer = () => {
const [name, setName] = useState(``)
const nameChange = (event) => {
setName(event.target.value)
}
return <div>
<input label="name: " id="name" onClick={nameChange} />
<input type="number" name="quantity" />
<button> Add </button>
<p> {name} </p>
</div>
}
as u can see, the onClick is on the input and thats why it works when pressing the inputbox, but, when i switch the onClick location to the button, it shows nothing, because there arent any value inserted to the button, obviously, any help?
You are using the onClick property (in onClick={nameChange}). This means your nameChange function gets called every time a user clicks into the input box.
You should change this to onChange={nameChange} and add the value={name} to the input:
<input label="name: " id="name" onChange={nameChange} value={name} />
This means that the nameChange function gets called every time the input changes. The value will also be set to name, so if anything else calls nameChange, it will be reflected in the input box.
Use the onChange event in the input field. And use the useEffect hook and its dependency to get the current data
useEffect(() => {
console.log('name', name);
}, [name])
<input type="string" onChanhe={(e:any) => nameChange(e.target.value)} />
<p>{name}</p>
I have a form that renders dynamiclly as a List of inputs like so
arrState.map((obj,index)=>{
return(
<input type="text" value={obj} onChange{(e) => stateHandler(e,index)}<input/>
)
})
this works perfectly however only if I run it in the main return of the form however I want to clean my code up and make a seperate object for this section of the form, when I do this it still works but when I change the value the input unfocuses, How would I go about this?
nevermind if you create a jsx function that is outside of the scope of the form and just pass the state and stateHandler as props it works, just if anyone needs it this was my solution
function InputMap({stateHandler, arrState}){
arrState.map((obj,index)=>{
return(
<input type="text" value={obj} onChange={(e) => stateHandler(e,index)}>
</input>
)
})
}
function Form(){
const [state, setState] = useState([])
function stateHandler(e,index){
// state handler
let temp = [...state]
temp[index] = e.target.value
setState(temp)
}
return(
<Form>
<InputMap stateHandler={stateHandler, state}/>
</Form>
)
}
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
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>
);
}
Story:
I have a form, and I want to do things with the values of that form. For background, I'm using react and react-bootstrap to make this form, though I'm more than willing to use a simple form (without react-bootstrap) if it proves simpler.
My form:
<form>
<FormGroup controlId="formControlsSelect" className={classes.formGroup}>
<ControlLabel className={classes.exportMessage}>Export</ControlLabel>
<FormControl className={classes.selectControl} ref='exportType'
componentClass="select" placeholder="Choose Option">
<option value="text">Plain text</option>
<option value="html">Simple HTML</option>
</FormControl>
</FormGroup>
<Button className={'cdm-btn' + ' ' + classes.modalButton} bsStyle='default'
onClick={this.handleClose}>Cancel</Button>
<Button className={'cdm-btn' + ' ' + classes.modalButton} bsStyle='primary'
type='submit' onSubmit={this.handleOnSubmit}>
<FontAwesome className={classes.download} name="download" />Export</Button>
</form>
Details
I have 1 input of type select (not sure if I'm saying this correctly?)
This form is within a modal that pops up after clicking a button and handleClose closes the modal.
I want to be able to use the value of the select as a parameter in a fetch call for later.
I'm having trouble getting this value
What I'm doing:
On submit:
handleOnSubmit(e) {
e.preventDefault();
// formSelectValue = ???
console.log(this.refs.exportType);
// fetchAndDownloadExportFile(listOfItems, formSelectValue);
this.handleClose();
}
This isn't working. the ref isn't output to the console. The page refreshes, but just before it does, I receive an error in the console:
Error in event handler: TypeError: Cannot read property 'getCurrent' of undefined at e (chrome-extension://blahblah)
What I've Tried:
I tried removing type="submit" from the Export button, using onClick instead, and it does then print out the ref'd FormControl, but I don't see anything indicating which of the two options I've selected.
Final:
All I want is to be able to select one of two options from a dropdown, plain text value="text" or simple html value="html" and then pass that value as a parameter into a function, (unrelated) which I can then use in a fetch.
Other possibly useful info: I'm fetching from an API endpoint with
#RequestMapping(
value = '/api/export',
method = RequestMethod.POST,
consumes = [MediaType.APPLICATION_JSON_VALUE],
produces = [MediaType.TEXT_HTML_VALUE, MediaType.TEXT_PLAIN_VALUE]
)
You need to do this the react way, which is keeping the value of the select input in a state and retrieving it whenever you need it. To keep the select value in a state, add an onChange event handler on the select input like this:
<FormControl className={classes.selectControl} componentClass="select" placeholder="Choose Option" onChange={this.handleChange} name="mySelectInput">
Notice I have added a name property to the select input
With thehandleChange as shown below:
handleChange = (evt)=> { // If you are using typescript, type evt like this evt: React.ChangeEvent<HTMLInputElement>
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
The handleChange function will save the value of the select input in the state. Now you can retrieve it and use it like this:
const {mySelectInput} = this.state;
Below is a full example you can take a look at:
class MyAwesomeComponent extends React.Component {
constructor() {
super()
this.state = {
mySelectInput: ""
}
this.handleOnSubmit = this.handleOnSubmit.bind(this);
this.handleChange = this.handleChange.bind(this)
}
handleChange = (evt)=> {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleOnSubmit(e) {
e.preventDefault();
// retrieve the value of the select input like this
const {mySelectInput} = this.state;
// and use it here
}
render(){
return(
<form>
<FormGroup controlId="formControlsSelect" className={classes.formGroup}>
<ControlLabel className={classes.exportMessage}>Export</ControlLabel>
<FormControl className={classes.selectControl} componentClass="select" placeholder="Choose Option" onChange={this.handleChange} name="mySelectInput">
<option value="text">Plain text</option>
<option value="html">Simple HTML</option>
</FormControl>
</FormGroup>
<Button className={'cdm-btn' + ' ' + classes.modalButton} bsStyle='default'
onClick={this.handleClose}>Cancel</Button>
<Button className={'cdm-btn' + ' ' + classes.modalButton} bsStyle='primary'
type='submit' onSubmit={this.handleOnSubmit}>
<FontAwesome className={classes.download} name="download" />Export</Button>
</form>
)
}
}
Your handleOnSubmit(e) function doesn't have the right event that you are looking for.
You need to watch for the select input event with a change handler and then save the updated value somewhere (such as state) so then you can use that value in your handleOnSubmit function