Set textarea to pristine after submit in React - reactjs

In my React component there is a required textarea that shouldn't submit empty. After submit I stay within the same component so the textarea has red borders to indicate its errored state.
const CommentForm = ({ postId, addComment }) => {
const [text, setText] = useState('');
const onSubmit = evt => {
evt.preventDefault();
addComment(postId, text);
setText('');
};
const onChange = evt => {
setText(evt.target.value)
};
return (
<div className='post-form'>
<div className='bg-primary p'>
<h3>Add a Comment</h3>
</div>
<form className='form my-1' onSubmit={onSubmit}>
<textarea
name='text'
placeholder='Comment on this post...'
required
value={text}
onChange={onChange}
/>
<input type='submit' className='btn btn-dark my-1' value='Submit' />
</form>
</div>
);
};
How do I remove the red borders after submitting a non empty value? The complete component code is at https://github.com/ElAnonimo/leansquad/blob/master/src/components/post/CommentForm.js.

Related

React js firebase empty field validation

I have created a form in react and store the details in firebase but my problem is even if the feilds are empty the form is submitted, i want validation that feild should not be empty if the user wants to submit.
const Account2 = () => {
const [kookid, setKookID] = useState("");
const [kookname, setKookName] = useState("");
const userCollectionRef = collection(db, "mastermenu")
const handleSubmit = () => {
addDoc(userCollectionRef,{
kookid: kookid,
kookname: kookname,
}).then(() => {
if(!alert("form Submitted Successfully!!!"));
navigate("/account");
})
return (
<><div className='outer-container'>
<h1 className='text-3xl font-bold py-2'>MASTER MENU</h1>
</div>
<div className='outer-container'>
<form className='contactform'>
<label>Kook ID</label>
<input
placeholder=""
onChange={(e) => setKookID(e.target.value) } />
<label>Kook Name</label>
<input
required
placeholder=""
onChange={(e) => setKookName(e.target.value)} />
</form>
<button onClick={handleSubmit}>Submit</button>
</div></>
)
}

Need little help on React hooks

I try to make a todo list with React and Redux Toolkit. In handleSubmit function to add item on list, my setText somehow not set the value to empty string.
Here are my full code on Stackblitz: https://stackblitz.com/edit/react-ts-bqmjz1?file=components%2FTodoForm.tsx
const TodoForm = (): JSX.Element => {
//Input value
const [text, setText] = useState('');
const dispatch = useDispatch();
//setText not working
const handleSubmit = (e: any) => {
e.preventDefault();
if (text.trim().length === 0) {
return;
}
dispatch(addItem({ title: text }));
setText('');
};
return (
<form className="container-fluid" onSubmit={handleSubmit}>
<div className="input-group">
<input
className="form-control"
placeholder="Enter the value..."
onChange={(e: { target: HTMLInputElement }) =>
setText(e.target.value)
}
/>
{/* Submit button */}
<button type="submit" className="btn btn-primary">
Add
</button>
</div>
</form>
);
};
You're very close! You just missed the value prop on the input:
value={text}
const TodoForm = (): JSX.Element => {
//Input value
const [text, setText] = useState('');
const dispatch = useDispatch();
//setText not working
const handleSubmit = (e: any) => {
e.preventDefault();
if (text.trim().length === 0) {
return;
}
dispatch(addItem({ title: text }));
setText('');
};
return (
<form className="container-fluid" onSubmit={handleSubmit}>
<div className="input-group">
<input
className="form-control"
placeholder="Enter the value..."
value={text}
onChange={(e: { target: HTMLInputElement }) =>
setText(e.target.value)
}
/>
{/* Submit button */}
<button type="submit" className="btn btn-primary">
Add
</button>
</div>
</form>
);
};
If I understood well the input does not become empty when you click on the add button. To do that you just have to add value={text} in your input
<input
className="form-control"
placeholder="Enter the value..."
value={text}
onChange={(e: { target: HTMLInputElement }) =>
setText(e.target.value)
}
/>

how to get the data from a component within a form in react

I have a with the following structure in react...
<form>
<div>
<label>Name</label>
<input />
</div>
<div>
<label>Age</label>
<input />
</div>
<div>
<label>Gender</label>
<input />
</div>
<AddressComponent />
<button type='submit'>
Submit
</button>
</form>
Does anyone know if there is a way for me to pass the AddressComponent data up to the parent form component onSubmit? The AddressComponent has a lot of state to manage and a load of functions and it appears a few more times across my website and so I don't want to keep repeating the same code over and over again.
Anyone know if there's a way for me to pass the AddressComponent state up to the parent form component onSubmit?
you can use ref to get access to the child functions so:
const AddressComponent = ({}, ref) => {
const [data, setData] = useState();
useImperativeHandle(ref, () => ({
getData: getData,
}));
const getData = () => {
return data;
}
return <div></div>;
};
export default React.forwardRef(AddressComponent);
and you can get data in your parent and in submit like this:
const ParentComponent = () => {
const AddressRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
const data = AddressRef.current.getData();
}
return (
<form onSubmit={handleSubmit}>
<div>
<label>Name</label>
<input />
</div>
<div>
<label>Age</label>
<input />
</div>
<div>
<label>Gender</label>
<input />
</div>
<AddressComponent ref={AddressRef} />
<button type='submit'>
Submit
</button>
</form>
)
}

how to invoke and change the value of a component on handleSubmit in react

I am coding with react. I created a Form and on submit I want to send the value of the input field as parameter of another react component, here is "cypher_query" of . Here is my code, it's not working, I don't know where I did mistake. Please help 🙏
const AppGraph = () => {
const [query, setQuery] = useState("");
const handleSubmit = (evt) => {
evt.preventDefault();
}
return (
<div>
<form id="myForm" onSubmit={handleSubmit} >
<div className="App" style={{ fontFamily: "Quicksand" }}>
<label htmlFor="CommentsOrAdditionalInformation">enter your query</label>
<input
name = "requete"
type="text"
id="CommentsOrAdditionalInformation"
value = {query}
onChange={e => setQuery(e.target.value)}
>
</input>
<input type = "submit" value="Submit" className="btn_submit" alt = "submit Checkout"/>
</div>
<p>{query}</p>
</form>
{<ResponsiveNeoGraph
containerId={"id0"}
neo4jUri={NEO4J_URI}
neo4jUser={NEO4J_USER}
neo4jPassword={NEO4J_PASSWORD}
cypher_query={query}
/>}
</div>
);
};
export default AppGraph;

React: How to clear file input and data input fields after submitting form?

After I submit my form, which contains data fields and a file field, only the data fields are cleared, but the uploaded file field is kept. See image: Here
OnChange Function
onChange = (e) => {
if(e.target.name === 'audio') {
this.setState({
[e.target.name]: e.target.files[0], loaded: 0,
}, () => console.log(this.state.audio))
} else {
this.setState({
[e.target.name]: e.target.value
}, () => console.log(this.state))
}
}
Submit Function
onSubmit = e => {
e.preventDefault();
let { title, content, audio} = this.state;
//const story = { title, content, audio};
let formDataStory = new FormData();
formDataStory.append('audio', audio);
formDataStory.append('title', title);
formDataStory.append('content', content);
this.props.addStory(formDataStory);
this.setState({
title: "",
content:"",
audio: ""
});
};
Form
render() {
const {title, content, audio} = this.state;
return (
<div className="card card-body mt-4 mb-4">
<h2>Add Story</h2>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Title</label>
<input
className="form-control"
type="text"
name="title"
onChange={this.onChange}
value={title}
/>
</div>
<div className="form-group">
<label>Content</label>
<input
className="form-control"
type="text"
name="content"
onChange={this.onChange}
value={content}
/>
</div>
<div className="form-group">
<label>Audio</label>
<input
className="form-control"
type="file"
name="audio"
onChange={this.onChange}
//value={audio}
/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">
Submit
</button>
</div>
</form>
</div>
);
}
}
How can I reset the file upload field together with the other data fields after submitting the form?
Many thanks!
Since the file input is always uncontrolled you'll need to use a dom ref and manually clear the value.
Here's an example functional component that does this:
function ExampleFileInput() {
const ref = React.useRef();
function handleClick() {
ref.current.value = ""
}
return (
<div className="App">
<input type="file" ref={ref}/><br />
<button type="button" onClick={handleClick}>Clear file</button>
</div>
);
}
To use in a class component, see the docs. You can read about more ways to clear the file input in this question.
Docs
Create ref to file input this.inputRef = React.createRef();
add ref to input <input type="file" ref={this.inputRef} />
Inside submit function this.inputRef.current.value = '';
If you use Formik you can do this:
I had the same issue and I managed it creating a ref in the parent component (the one that use Formik) and passing it to the Field using innerRef prop.
Then on the onReset I used the ref to clear the real input value.
const UserForm = props => {
const logoRef = useRef();
const handleReset = (values, formikBag) => {
logoRef.current.value = null; //THIS RESETS THE FILE FIELD
}
const handleSubmit = (values, formikBag) => {
//...
axios({method, url, data})
.then(response => {
formikBag.resetForm();
})
}
//...
return (
<Formik initialValues={initialValues} onSubmit={handleSubmit} onReset={handleReset}>
...
<Field
type="file"
name="logo"
onChange={({target}) => setFieldValue(props.name, target.files[0])}
innerRef={logoRef}
/>
</Formik>
)
}

Resources