How do I reset this.fileInput to empty or null or undefined?
class FileInput extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.fileInput = React.createRef(); }
handleSubmit(event) {
event.preventDefault();
alert(`Selected file - ${this.fileInput.current.files[0].name}`);
// Assume I have uploaded the file here
// How do I reset this.fileInput to empty Ref?
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Upload file:
<input type="file" ref={this.fileInput} /> </label>
<br />
<button type="submit">Submit</button>
</form>
);
}
}
ReactDOM.render(
<FileInput />,
document.getElementById('root')
);
You can use input type="reset"
<form onSubmit={this.handleSubmit}>
<label>
Upload file:
<input type="file" ref={this.fileInput} /></label>
<br />
<input type="reset" defaultValue="Reset" />
<button type="submit">Submit</button>
</form>
You actually trying to "reset" the form, so you should call HTMLFormElement.reset().
export default class FileInput extends React.Component {
fileInput = React.createRef();
formRef = React.createRef();
handleSubmit = (event) => {
event.preventDefault();
alert(`Selected file - ${this.fileInput.current.files[0].name}`);
this.formRef.current.reset();
};
render() {
return (
<form ref={this.formRef} onSubmit={this.handleSubmit}>
<label>
Upload file:
<input type="file" ref={this.fileInput} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
}
just clear the value of your ref
this.fileInput.current.value = ''
Related
I am using react hook forms to create forms in my application:
import "./styles.css";
import { useForm } from "react-hook-form";
export default function App() {
const { register, setFocus, handleSubmit } = useForm({
defaultValues: { inputText: "", inputCheckbox: false }
});
const onSubmit = (data) => {
console.log(data);
};
return (
<div className="App">
<form onSubmit={handleSubmit(onSubmit)} className="form">
<br />
<label>inputCheckbox</label>
<input type="checkbox" {...register("inputCheckbox")} />
<br />
<br />
<label>inputCheckbox2</label>
<input type="checkbox" {...register("inputCheckbox")} />
<button
onClick={() => {
setFocus("inputCheckbox");
}}
>
setFocus inputCheckbox
</button>
<br />
<br />
<button type="submit">Submit</button>
</form>
</div>
);
}
I try to set focus when i click on the button, but it does not work, why and how to fix using the library API?
demo: https://codesandbox.io/s/icy-feather-eh1crv?file=/src/App.js:0-899
I've made a form in ReactJS with one text input and when it submits I want to get its value and put it into a variable. But when I console.log() it returns as undefined. How do I fix this? Here is my code.
class App extends Component {
state = {
todoTitle: ""
};
render() {
return (
<div>
<center>
<form
onSubmit={(event) => {
event.preventDefault();
this.setState(todoTitle: event.target.value,);
console.log(this.state.todoTitle); // Returns "undefined"
}}
>
<input
type="text"
autocomplete="off"
class="form-control"
name="todoInput"
placeholder="Enter todo"
style={{ width: "400px", height: "50px" }}
/>
<input
type="submit"
value="Submit"
id="submitButton"
></input>
</form>
</center>
}
}
}
You need to either make a controlled input or useRef for un-controlled input for the React to keep track of your todoTitle state.
To make a controlled input, you will need to use onChange event and a value={this.state.todoTitle} property.
Also on your form, it is best to add an onSubmit event. There is however an option to set the submit on the form submit button also. In that case we need to use onClick={this.handleSubmit} as follows <input type="submit" value="Submit" id="submitButton" onClick={this.handleSubmit} />.
The below code will work for you:
class Form extends React.Component {
state = {
todoTitle: "",
};
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state.todoTitle);
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
autocomplete="off"
class="form-control"
name="todoInput"
placeholder="Enter todo"
style={{ width: "400px", height: "50px" }}
value={this.state.todoTitle}
onChange={(e) => this.setState({ todoTitle: e.target.value })}
/>
<input type="submit" value="Submit" id="submitButton" />
</form>
</div>
);
}
}
You can modify your app a bit to get the value on onChange of input textfield, and then store it in the array in case of below example:
export default class App extends React.Component {
state = {
todoTitle: "",
todoList: []
};
render() {
return (
<div>
<center>
<form
onSubmit={event => {
event.preventDefault();
this.setState(
{
todoList: [...this.state.todoList, this.state.todoTitle]
},
() => {
console.log(this.state.todoList);
}
);
}}
>
<input
type="text"
autocomplete="off"
class="form-control"
name="todoInput"
placeholder="Enter todo"
onChange={event => {
this.setState({ todoTitle: event.target.value });
console.log(event.target.value);
}}
style={{ width: "400px", height: "50px" }}
/>
<input type="submit" value="Submit" id="submitButton" />
</form>
</center>
</div>
);
}
}
Full app here: Stackblitz
There are a few other errors with your code, but I will just answer your question.
setState triggers a re-render, so your state isn't available to log until the next time it runs. You can just log what you put in setState.
console.log(event.target.value);
This question has more info.
setState doesn't update the state immediately
Also, you can do a callback.
this.setState({ todoTitle: event.target.value }, () =>
console.log(this.state.todoTitle)
);
Try this:
class App extends React.Component {
constructor(props) {
super(props);
this.state = { todoTitle: "" };
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
event.preventDefault();
this.setState({ todoTitle: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
console.log(this.state.todoTitle);
}
render() {
return (
<div>
<center>
<form onSubmit={this.handleSubmit}>
<input
type="text"
autocomplete="off"
class="form-control"
name="todoInput"
placeholder="Enter todo"
style={{ width: "400px", height: "50px" }}
onChange={this.handleChange}
/>
<input type="submit" value="Submit" id="submitButton" />
</form>
</center>
</div>
);
}
}
This will change the state on input changes and then logs on submit the state. An alternative would be to just get the input element and its value via getElementById or something similar in React.
Your code was also not very well formatted and a lot of closing tags missed.
Read more here:
Get form data in ReactJS
I am new to react and have this form:
class CustomForm extends React.Component {
handleFormSubmit = (e) => {
e.preventDefault();
const title = e.target.elements.title.value;
const content = e.target.elements.content.value;
console.log(title, content)
}
render() {
return (
<div>
<Form onSubmit={ this.handleFormSubmit }>
<FormItem label='Title'>
<Input name='title' placeholder='Put a title here' />
</FormItem>
<FormItem label='Content'>
<Input name='content' placeholder='Enter some content' />
</FormItem>
<FormItem>
<Button type='primary' htmlType='submit'>Submit</Button>
</FormItem>
</Form>
</div>
)
}
}
The form is not submitting anything/nothing in console log. I tried it with onSubmitCapture and that seems to work. How do I fix this?
From your code it looks like you are using some custom component <Form>.. this is not the normal <form> because custom <Form> component might not have the prop onSubmit. Go through the documentation of the component you are using.
button with type='submit' will trigger the form onSubmit Handler
You need to bind the event handlers in the constructor in order to work. Read more here https://reactjs.org/docs/handling-events.html:
class CustomForm extends React.Component {
constructor(props) {
super(props)
this.handleFormSubmit = this.handleFormSubmit.bind(this)
}
handleFormSubmit = (e) => {
e.preventDefault();
const title = e.target.elements.title.value;
const content = e.target.elements.content.value;
console.log(title, content)
}
render() {
return (
<div>
<Form onSubmit={ this.handleFormSubmit }>
<FormItem label='Title'>
<Input name='title' placeholder='Put a title here' />
</FormItem>
<FormItem label='Content'>
<Input name='content' placeholder='Enter some content' />
</FormItem>
<FormItem>
<Button type='primary' htmlType='submit'>Submit</Button>
</FormItem>
</Form>
</div>
)
}
}
In my component, I'm trying to call in an handleChange and handleSubmit functions of a component
If I render like the forms example,
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.value} onChange={this.handleChange} placeholder="Enter new title"/>
<input type="submit" value="Submit" />
</form>
in onChange(), this won't be bound to the component, and I can't call this.setState, so I bind it with onChange={() => this.handleChange}.
for onSubmit(), I have the same binding problem, but when I bind it, the handler is not called, and the page is reloaded. What is the right way to bind to the component when submitting?
TIA
Full example:
class CbList extends React.Component {
constructor() {
super();
this.state = {
newTitle: '',
list: []
};
}
handleChange(event) {
this.setState(Object.assign({},
this.state,
{ newTitle: event.target.value }));
}
handleSubmit(event) {
this.addBlock(this.state.newTitle);
event.preventDefault();
return false;
}
render() {
return (
<div className="cb-list">
<div>
<form onSubmit={() => this.handleSubmit}>
<input type="text" value={this.state.value} onChange={() => this.handleChange}
placeholder="Enter new title"/>
<input type="submit" value="Submit" />
</form>
</div>
</div>
);
}
addBlock(title) {
let updatedList = this.state.list.concat({ title: title });
this.setState({ list: updatedList })
}
};
$(function() {
ReactDOM.render(<CbList/>, $('#home').get(0));
});
You forgot to invoke the functions:
onSubmit={()=>this.handleSubmit}
should be
onSubmit={()=>this.handleSubmit()}
Or, just pass a reference to the function:
onSubmit={this.handleSubmit}
but you'll need to bind your functions in the constructor (as show in the forms example link):
this.handleSubmit = this.handleSubmit.bind(this);
You need to bind you event handlers on constructor so you can use them among other events.
constructor(props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
}
Also, you don't need arrow function when using then as props.
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
placeholder="Enter new title"
/>
<input type="submit" value="Submit" />
</form>
class Form extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const { Add, noteList } = this.props;
Add('this is title's value' , 'this is content's value');
}
render() {
const { handleSubmit, noteList: { list } } = this.props;
return (
<form onSubmit={handleSubmit(this.handleClick)}>
<div>
<Field className="title" name="title" component="input" type="text" />
</div>
<div>
<Field className="content" name="content" component="textarea" />
</div>
<div>
<button type="submit" onClick={(e) => { list ? this.handleClick : e.preventDefault(); }}>add</button>
</div>
</form>
);
}
}
when i click the button, i hope to get these two values into a function Add as two arguments to do something async, what should i do , help me please
The field values in handleClick function can can be obtained onSubmit as an object.
class Form extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(values) {
const { Add, noteList } = this.props;
Add(values.title , values.content);
}
render() {
const { handleSubmit, noteList: { list } } = this.props;
return (
<form onSubmit={handleSubmit(this.handleClick)}>
<div>
<Field className="title" name="title" component="input" type="text" />
</div>
<div>
<Field className="content" name="content" component="textarea" />
</div>
<div>
<button type="submit" onClick={(e) => { list ? this.handleClick : e.preventDefault(); }}>add</button>
</div>
</form>
);
}
}