Trigger "tick box" message in checkbox field - reactjs

I am using React, and I would like to find a way to trigger this message (that now triggers only when pressing the type="submit" button, on will, is there any action I can use to trigger this message at any point (for example if a user presses any other button)
<input
id="conditions"
type="checkbox"
name="conditions"
ref={acceptConditions}
required
></input>

This can be achieved with reportValidity() MDN documentation
setTimeout(() =>
document.getElementById('example').reportValidity(),
3000
)
<input id="example" type="checkbox" required />

Ok here are a few approaches, that works.
approach 1
Using the reportValidity()
This function will check the validity of the element and then trigger the event.
import { useRef } from "react";
import "./styles.css";
export default function App() {
const acceptConditions = useRef();
const formRef = useRef();
const handleSubmit = () => {
acceptConditions.current.reportValidity();
};
return (
<form ref={formRef}>
<input
id="conditions"
type="checkbox"
name="conditions"
ref={acceptConditions}
required
></input>
<span>Tick this box to continue</span>
<br />
<button type={"submit"}>submit the form</button>
<br />
<button onClick={handleSubmit}>Imposter button</button>
</form>
);
}
This is a good apporach And one that i recommend.
approach 2:
First of all if you want any other button to trigger the same event then you can do is make a reference to the form and then submit the form manually on the button press.
Here is an example.
import { useRef } from "react";
import "./styles.css";
export default function App() {
const acceptConditions = useRef();
const formRef = useRef();
const handleSubmit = () => {
console.log(formRef.current.submit);
};
return (
<form ref={formRef}>
<input
id="conditions"
type="checkbox"
name="conditions"
ref={acceptConditions}
required
></input>
<span>Tick this box to continue</span>
<br />
<button type={"submit"}>submit the form</button>
<br />
<button onClick={handleSubmit}>Imposter button</button>
</form>
);
}
in the above code the imposter button will trigger the same action as the button with the type="submit".
thank you.

Related

Why is the function not implemented when I submitted the form?

The function I pass to the onsubmit event is not executed when the form is submitted
import React from 'react';
import styles from './Form.module.css';
import Button from './Button';
const Form = function (props) {
const addUserHandler = function (e) {
e.preventDefault();
console.log(135);
};
return (
<form onSubmit={addUserHandler}>
<input
type='text'
className={styles.input}
placeholder='Your Age'
ref={nameInputRef}
/>
<Button type='submit'>add user</Button>
</form>
);
};
export default Form;
I expected that the function adduserhandler will be executed when I submitted the form.
You are not passing the type correctly from <Button> to <button>, which means that the submit button is rendered as a normal button which does not submit the form. Instead of:
<button type={props.type ? 'button' : props.type}>
do:
<button type={props.type ? props.type : 'button'}>
or shorter:
<button type={props.type || 'button'}>

Radio button with form in Function Component (React) =>get Warning from the Console

I try to collect data from inputs and pass it down to next pages, after adding radio button in the form, the code works fine, however, the Browser Console on Chrome gives me warnings like following:
Warning: You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.
What does that mean? And how to solve it?
(I'm new to the React. Appreciate for your time)
the following is the code:
import {useLocation} from 'react-router-dom';
import { useState } from "react";
import { useNavigate } from "react-router-dom";
const Second = () => {
const navigate = useNavigate();
const location = useLocation();
const contact=location.state;
const [name, setName] = useState("");
const [wording, setWording] = useState("");
const handleSecSubmit = (e) => {
e.preventDefault();
const contacttotal={
...contact,
...{name},
...{wording}
};
console.log(contacttotal);
navigate("/final", { state: { contacttotal } });
}
return (
<div className="Second">
<h1>This is Second Input Page</h1>
<form autoComplete="on" onSubmit={handleSecSubmit}>
<dd>Name</dd>
<input
type="text"
value={name}
onChange={(e) =>
setName(e.target.value)
}
required
></input>
<dd>Wording</dd>
<div>
<div onChange={(e) => setWording(e.target.value)}>
<label><input
type="radio"
value='United States'
name="wording"
checked={wording === "United States"}
/>United States</label>
<label><input
type="radio"
value='British'
name="wording"
checked={wording === "British"}
/>British</label>
</div>
</div>
<br/>
<button>submit</button>
</form>
</div>
);
}
export default Second;
Simply add onChange event to every input.
<input
type="radio"
value='United States'
name="wording"
checked={wording === "United States"}
onChange={(e) => setWording(e.target.value)}
/>
And remove it from the div. It's not the best idea to use onChange event on other elements than input, textarea or select.

How to open input fields based on radio button selection in React?

I have two radio buttons. Based on which radio button is selected, I need to open input fields to collect some data. How can I achieve this using react?
I tried manipulating the onClick and onChange functions.
Here is the code
import { useState, useEffect } from 'react';
const App = () => {
const [itWorks, setItWorks] = useState(false)
function handleClick(){ SetItWorks(!itworks) }
return (
<div>
{itWorks ?
<>
'It works!'
<input type="text" />
</>: 'It does not'}
<button onClick={() => setItWorks(!itWorks)} >Press me
<input type='radio' aria-selected onClick={handleClick} />
</div>
) }
export default App;

OnSubmit event not fired with preventDefault on the container

Would somebody explain to me why the submit callback is not called when I try to submit the form (using the button or by pressing enter) ?
The reason is this onClick event on the container but I cannot grasp why...
Shouldn't the submit event be caught by the form before bubbling up to the div with onClick?
export default function App() {
const [val, setVal] = useState("");
function submit() {
alert(val);
}
function prevent(e) {
e.preventDefault();
}
return (
<div className="App" onClick={prevent}>
<form onSubmit={submit}>
<input
name="test"
value={val}
onChange={(e) => setVal(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
</div>
);
}
codesandbox
Edit:
My form is inside an 'a' tag and because of that, I wanted to use preventDefault so the user to not be redirected when filling up the form.
Thanks in advance!
I am not sure what you are trying to achieve here, but preventing default actions on the parent element is not actually the best thing to do. Your code could have been better this way:
export default function App() {
const [val, setVal] = useState("");
function submit(e) {
e.preventDefault();
alert(val);
}
return (
<form onSubmit={(e) => submit(e)}>
<input
name="test"
value={val}
onChange={(e) => setVal(e.target.value)}
/>
<button type="submit">Submit</button>
</form>);
}
The prevent() function is unnecessary and have no meaningful impacts on your code. Keeping it simple and sweet is the best way to go.

How to get textarea data with useState()

I have read page after page and I am not sure what I am doing wrong. My useState works with my other inputs. I am unable to get it to work with my textarea.
Also, what would be the best way to use my data in another component?
import React, { useState } from "react";
const OrderItems = () => {
const [commentText,setCommentText] = useState("")
const onSubmit = (data) => {
console.log(data.commentText);
}
return (
<>
<form id="myForm" onSubmit={handleSubmit(onSubmit)} >
<div>
<label
htmlFor="CommentsOrAdditionalInformation">Comments or Additional Information</label>
<textarea
name = "commentTextArea"
type="text"
id="CommentsOrAdditionalInformation"
value = {commentText}
onChange={e => setCommentText(e.target.value)}
>
</textarea>
</div>
</form>
<button type = "submit" form ="myForm" className="btn_submit" alt = "submit Checkout">
<a href ="/cart/preview"/>
<img src = ""/>
</button>
</>
)
}
You are initializing state outside the function, Please do it like this:
Also, You are logging the wrong state inside onSubmit.
import React, { useState } from "react";
const OrderItems = () => {
const [commentText,setCommentText] = useState("")
const handleSubmit = (evt) => {
evt.preventDefault();
console.log(commentText);
}
return (
<>
<form id="myForm" onSubmit={handleSubmit} >
<div>
<label
htmlFor="CommentsOrAdditionalInformation">Comments or Additional Information</label>
<textarea
name = "commentTextArea"
type="text"
id="CommentsOrAdditionalInformation"
value = {commentText}
onChange={e => setCommentText(e.target.value)}
>
</textarea>
<input type = "submit" value="Submit" className="btn_submit" alt = "submit Checkout"/>
</div>
</form>
</>
)
}
To use the data in another component: If it is a child component pass it as props. Else use state management tools like context or redux.
Also, for routing, I would recommend using React Router. Refer here.
Some things to keep in mind:
import React, { useState } from "react";
const OrderItems = () => {
// Always initialise state inside the component
const [commentText,setCommentText] = useState("")
const handleOnSubmit = event => {
event.preventDefault();
console.log(commentText);
}
return (
// onSubmit should just be a reference to handleOnSubmit
<form id="myForm" onSubmit={handleOnSubmit} >
<div>
<label
htmlFor="CommentsOrAdditionalInformation">Comments or Additional Information
</label>
// You can self-close the textarea tag
<textarea
name="commentTextArea"
type="text"
id="CommentsOrAdditionalInformation"
value={commentText}
onChange={e => setCommentText(e.target.value)}
/>
</div>
// Put the button inside the form
<button type = "submit" form ="myForm" className="btn_submit" alt="submit Checkout">
<a href ="/cart/preview"/>
<img src = ""/>
</button>
</form>
);
}

Resources