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

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'}>

Related

Trigger "tick box" message in checkbox field

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.

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;

React: invoke props in a function

Fairly new to React so please let me know if I'm approaching this wrong.
In short, I want to be able to redirect to the login component after a form has been submitted in the signUp component.
When we click on a signUp or login button it changes the currentPage state to the assigned value. For example if currentPage is currently set to "Login" it will load the Login component and "Sign Up" with the Sign Up component. The components load as they should but when trying to pass in the props in the SignUp component I can't figure out how to invoke the pageSetter function after the form has been submitted.
I could just do the below, which works but I only want to invoke it in the onSubmit function
<form onSubmit={this.props.pageSetter}>
import React from "react";
function Button(props) {
return (
<button id={props.id} value={props.value} onClick={props.onClick}>
{props.value}
</button>
);
}
export default Button;
import SignUp from "./components/signUp.jsx";
import Login from "./components/login.jsx";
class App extends Component {
state = {
currentPage: "Login",
};
pageSetter = ({ target }) => {
this.setState({ currentPage: target.value });
};
render() {
return (
<div>
{this.state.currentPage !== "Sign Up" && (
<Button id={"signUp"} value={"Sign Up"} onClick={this.pageSetter} />
)}
{this.state.currentPage !== "Login" && (
<Button id={"login"} value={"Login"} onClick={this.pageSetter} />
)}
{this.state.currentPage === "Login" && <Login />}
{this.state.currentPage === "Sign Up" && (
<SignUp pageSetter={this.pageSetter} />
)}
</div>
);
}
}
export default App;
class SignUp extends Component {
myChangeHandler = (event) => {
let attribute = event.target.id;
let value = event.target.value;
this.setState({ [attribute]: value });
};
onSubmit = (event) => {
event.preventDefault();
this.props.pageSetter.value = "Login"
this.props.pageSetter
};
render() {
console.log(this.state);
return (
<div>
<form onSubmit={this.onSubmit}>
<p>real_name:</p>
<input id="real_name" type="text" onChange={this.myChangeHandler} />
<p>username:</p>
<input id="username" type="text" onChange={this.myChangeHandler} />
<p>email:</p>
<input id="email" type="text" onChange={this.myChangeHandler} />
<p>password:</p>
<input
id="password"
type="password"
onChange={this.myChangeHandler}
/>
<p>picture</p>
<input id="picture" type="text" onChange={this.myChangeHandler} />
<button id="userSubmit" type="submit">
Submit
</button>
</form>
</div>
);
}
}
export default SignUp;
I think there is a typo in your code example :
onSubmit = (event) => {
event.preventDefault();
this.props.pageSetter.value = "Login"
this.props.pageSetter
};
Could you please edit it and i'll check again if I can help !
Also, despite the typo, I don't understand why you try to set the property "value" on the props pageSetter which is a function.
I couldn't understand either why you're setting a property in a function. Instead of doing this, you should invoke the function using the value as argument.
this.props.pageSetter('Login');
You also should fix the pageSetter function to receive the page value instead of an event.

React - Form submit button in parent Modal

I have a Semantic UI Form:
import {Form} from 'semantic-ui-react';
<MyForm>
<Form onSubmit={_handleSubmit}>
<Form.Input name="myInput" label="My Label" value="" />
<Form.Group>
<Form.Button>Submit</Form.Button>
</Form.Group>
</Form>
</MyForm>
This form can be displayed inside a modal, or directly in a standard view in my app
My modal looks like this:
import {Button, Modal} from 'semantic-ui-react';
<Modal open={true} size="large" centered>
<Modal.Header>My Label</Modal.Header>
<Modal.Content>
<MyForm />
</Modal.Content>
<Modal.Actions>
<Button className="close-button">Cancel</Button>
{/* Insert submit button here*/}
</Modal.Actions>
</Modal>
This simple approach is working.
What I would like to do, is to have the submit button inside the Modal.Actions section when it's displayed in a modal, and keep it right after the input otherwise.
I don't know how to tell my form that the submit button is somewhere in its parent.
I finally managed to do it using a ref.
The idea is to create a ref in the form, pointing to the submit function and having a function in props to transmit this ref to my modal.
Modal:
import {Button, Modal} from 'semantic-ui-react';
const [submitFunc, setSubmitFunc] = useState();
const submitForm = () => {
if (submitFunc) {
submitFunc.current();
}
};
<Modal open={true} size="large" centered>
<Modal.Header>My Label</Modal.Header>
<Modal.Content>
<MyForm setSubmitFunc={setSubmitFunc} />
</Modal.Content>
<Modal.Actions>
<Button>Cancel</Button>
<Button onClick={submitForm}>Submit</Button>
</Modal.Actions>
</Modal>
Form:
function EditRecordForm({setSubmitFunc}) {
const submitRef = useRef(null);
useEffect(() => {
if (!!setSubmitFunc) {
setSubmitFunc(submitRef);
}
});
const handleSubmit = () => {
// Do whatever you need to retrieve form values and submit it
}
submitRef.current = handleSubmit;
return (
<MyForm>
<Form onSubmit={_handleSubmit}>
<Form.Input name="myInput" label="My Label" value="" />
<Form.Group>
<Form.Button>Submit</Form.Button>
</Form.Group>
</Form>
</MyForm>
)
}
What you can do is, you can associate the form with the button in the modal actions using a form id. Here is how you do it :-
Form:
<MyForm>
<Form id={'my-form'} onSubmit={_handleSubmit}>
{/*Form Elements}
</Form>
</MyForm>
Modal:
<Modal.Actions>
<Button>Cancel</Button>
<Button type={'submit'} form={'my-form'}>Submit</Button>
</Modal.Actions>
Following link is the tweet by the creator of chakr-ui telling the same method to join the form in a side drawer which needs to be connected to the button in the drawer footer.
https://twitter.com/thesegunadebayo/status/1330866834636201987?lang=en

How to make form component submit using button in form?

I have the following code where a text input box accepts an url and if it is valid it should create a display area and provide a nice preview of the url.
But I am not sure how to associate the submit from the button with the submit from the form.
import React, {useState} from 'react';
import './App.css';
import Microlink from '#microlink/react';
import { String } from 'core-js';
import Card from '#material-ui/core/Card';
import TextField from '#material-ui/core/TextField';
import Button from "#material-ui/core/Button";
function validURL(str) {
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
return !!pattern.test(str);
}
function App (){
const [myurl, setMyurl] = useState("")
const [display, setDisplay] = useState(true)
const handleChange = (event) => {
const url = event.target.value
var str = validURL(url)
console.log(str)
str ? setMyurl(String(url)) : setDisplay(false)
}
return (
<form>
<TextField
id="outlined-name"
label="Name"
margin="normal"
variant="outlined"
onSubmit={event => handleChange(event)}
/>
<Button
type="submit"
variant="contained"
>
Submit
</Button>
{display ?
<Card>
<Microlink url={myurl}/>;
</Card> : null}
</form>
)
}
export default App;
You need to put the onSubmit inside the form tag like this. Also need to have a controlled form. Meaning, you need an onChange, I wrote it for you.
return (
<form onSubmit={event => handleChange(event)} >
<TextField
id="outlined-name"
label="Name"
margin="normal"
variant="outlined"
value={myurl}
onChange={e => setMyUrl(e.target.value)}
/>
<Button
type="submit"
variant="contained"
>
Submit
</Button>
{display ?
<Card>
<Microlink url={myurl}/>;
</Card> : null}
</form>
)
}
export default App;

Resources