How to focus a Material UI Textfield on button click? - reactjs

How to focus a Textfield after clicking a button. I tried to use autoFocus but it did not work out: Example sandbox
<div>
<button onclick={() => this.setState({ focus: true })}>
Click to focus Textfield
</button>
<br />
<TextField
label="My Textfield"
id="mui-theme-provider-input"
autoFocus={this.state.focus}
/>
</div>

You need to use a ref, see https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus();
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<button onClick={this.focusTextInput}>
Click to focus Textfield
</button>
<br />
<TextField
label="My Textfield"
id="mui-theme-provider-input"
inputRef={this.textInput}
/>
</div>
);
}
}
Updated ref to inputRef for Material-UI v3.6.1.

if you are using a stateless functional component then you can use react hooks.
import React, { useState, useRef } from "react";
let MyFunctional = (props) => {
let textInput = useRef(null);
return (
<div>
<Button
onClick={() => {
setTimeout(() => {
textInput.current.focus();
}, 100);
}}
>
Focus TextField
</Button>
<TextField
fullWidth
required
inputRef={textInput}
name="firstName"
type="text"
placeholder="Enter Your First Name"
label="First Name"
/>
</div>
);
};

First, onclick must be correct like onClick,
then if you want to use it inline your JSX code, it can help.
I tested it with react 16, it works.
<button onClick={() => this.myTextField.focus()}>
Click to focus Textfield
</button>
<TextField
label="My Textfield"
id="mui-theme-provider-input"
inputRef={(el) => (this.myTextField = el)} />

If you are using Material-ui <TextField/> with react functional Component, you can implement focus using inputRef. The trick here is the if condition if(input != null). You can simply do:
<TextField
variant="filled"
inputRef={(input) => {
if(input != null) {
input.focus();
}
}}
/>
Here is an working example for you. CodeSandBox- Material-ui-TextFieldFocus

Related

How to set values in a multi-step Formik form with components that implement useField()

I'm implementing the multi-step wizard example with Material-UI components and it works well with the useField() hook but I cannot figure out how to bring setFieldValue() into scope, so I can use it from a wizard step.
I've seen suggestions to use the connect() higher-order component but I have no idea how to do that.
Here is a snippet of my code: CodeSandbox, and the use case:
A wizard step has some optional fields that can be shown/hidden using a Material-UI Switch. I would like the values in the optional fields to be cleared when the switch is toggled off.
I.e.
Toggle switch on.
Enter data in Comments field.
Toggle switch off.
Comments value is cleared.
Toggle switch on.
Comments field is empty.
Hoping someone can help! Thanks.
I came across this answer the other day but discarded it because I couldn't get it working.
It does actually work but I'm in two minds as to whether it's the right approach.
const handleOptionalChange = (form) => {
setOptional(!optional)
form.setFieldValue('optionalComments', '', false)
}
<FormGroup>
<FormControlLabel
control={
// As this element is not a Formik field, it has no access to the Formik context.
// Wrap with Field to gain access to the context.
<Field>
{({ field, form }) => (
<Switch
checked={optional}
onChange={() => handleOptionalChange(form)}
name="optional"
color="primary"
/>
)}
</Field>
}
label="Optional"
/>
</FormGroup>
CodeSandbox.
I believe this is what you're after: CodeSandbox. I forked your CodeSandbox.
I tried to follow your code as closely as possible and ended up not using WizardStep. The step variable is returning a React component that is a child to Formik. Formik is rendered with props e.g. setFieldValue, which can be passed down to its children. In order to pass the setFieldValue as a prop to step, I had to use cloneElement() (https://reactjs.org/docs/react-api.html#cloneelement), which allows me to clone the step component and add props to it as follows.
// FormikWizard.js
<Formik
initialValues={snapshot}
onSubmit={handleSubmit}
validate={step.props.validate}
>
{(formik) => (
<Form>
<DialogContent className={classes.wizardDialogContent}>
<Stepper
className={classes.wizardDialogStepper}
activeStep={stepNumber}
alternativeLabel
>
{steps.map((step) => (
<Step key={step.props.name}>
<StepLabel>{step.props.name}</StepLabel>
</Step>
))}
</Stepper>
<Box
className={classes.wizardStepContent}
data-cy="wizardStepContent"
>
{React.cloneElement(step, {
setFieldValue: formik.setFieldValue
})}
</Box>
</DialogContent>
<DialogActions
className={classes.wizardDialogActions}
data-cy="wizardDialogActions"
>
<Button onClick={handleCancel} color="primary">
Cancel
</Button>
<Button
disabled={stepNumber <= 0}
onClick={() => handleBack(formik.values)}
color="primary"
>
Back
</Button>
<Button
disabled={formik.isSubmitting}
type="submit"
variant="contained"
color="primary"
>
{isFinalStep ? "Submit" : "Next"}
</Button>
</DialogActions>
</Form>
)}
</Formik>
To access the setFieldValue prop in the child component, in App.js, I created a new component called StepOne and used it to wrap around the inputs, instead of using WizardStep. Now I am able to access setFieldValue and use it in the handleOptionalChange function.
// App.js
import React, { useState } from "react";
import "./styles.css";
import { makeStyles } from "#material-ui/core/styles";
import Box from "#material-ui/core/Box";
import CssBaseline from "#material-ui/core/CssBaseline";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import FormGroup from "#material-ui/core/FormGroup";
import Switch from "#material-ui/core/Switch";
import FormikTextField from "./FormikTextField";
import { Wizard, WizardStep } from "./FormikWizard";
const useStyles = makeStyles((theme) => ({
content: {
display: "flex",
flexFlow: "column nowrap",
alignItems: "center",
width: "100%"
}
}));
const initialValues = {
forename: "",
surname: "",
optionalComments: ""
};
const StepOne = ({ setFieldValue }) => {
const classes = useStyles();
const [optional, setOptional] = useState(false);
const displayOptional = optional ? null : "none";
const handleOptionalChange = () => {
setFieldValue("optionalComments", "");
setOptional(!optional);
};
return (
<Box className={classes.content}>
<FormikTextField
fullWidth
size="small"
variant="outlined"
name="forename"
label="Forename"
type="text"
/>
<FormikTextField
fullWidth
size="small"
variant="outlined"
name="surname"
label="Surname"
type="text"
/>
<FormGroup>
<FormControlLabel
control={
<Switch
checked={optional}
onChange={handleOptionalChange}
name="optional"
color="primary"
/>
}
label="Optional"
/>
</FormGroup>
<FormikTextField
style={{ display: displayOptional }}
fullWidth
size="small"
variant="outlined"
name="optionalComments"
label="Comments"
type="text"
/>
</Box>
);
};
function App(props) {
return (
<>
<CssBaseline />
<Wizard
title="My Wizard"
open={true}
initialValues={initialValues}
onCancel={() => {
return;
}}
onSubmit={async (values) => {
console.log(JSON.stringify(values));
}}
>
<StepOne />
<StepTwo />
</Wizard>
</>
);
}
export default App;
Alternative
To use setFieldValue in Formik, the easiest way would be to have the all input elements within the <Formik></Formik tags. You could conditionally render the input elements based on what step you're on as follows. This gives the inputs a direct access to setFieldValue so you can call setFieldValue("optionalComments", "") on the Switch input which will clear the comments on each toggle. Although this may mean you'll have a longer form, I don't think this is necessarily a bad thing.
<Formik>
<Form>
{step === 1 && <div>
// Insert inputs here
</div>}
{step === 2 && <div>
<TextField
onChange={(event) => setFieldValue("someField", event.target.value)}
/>
<Switch
checked={optional}
onChange={() => {
setFieldValue("optionalComments", "");
setOptional(!optional);
}}
name="optional"
color="primary"
/>
</div>}
</Form>
</Formik>

Formik Form not updating with onclick

I have a custom event handler (when clicked on a button) that injects data in the nested arrays based on a drop down selection. After the event handler added the data the form doesn't update properly. Calling any other event handler on any other input of the form will trigger the form update. The data is set correctly but the form doesnt update properly after the initial onClick event (see code)
I have enableReinitialize set
https://codesandbox.io/s/updateissue-fy72h
import { useEffect, useState } from "react";
import { Formik, Form, Field, FieldArray, TextField } from "formik";
export default function Design() {
const q = {
questions: ["a", "b", "c", "d"],
selectedLanguage: "nl",
};
const [questionnaire, setQuestionnaire] = useState(q);
function addLanguageValue() {
questionnaire.questions.push(questionnaire.selectedLanguage);
setQuestionnaire(questionnaire);
}
return (
<div>
<Formik
initialValues={questionnaire}
enableReinitialize
onSubmit={() => {}}
>
{({ values, handleChange }) => (
<Form>
<div>
<Field as="select" name="selectedLanguage">
<option value="fr">French</option>
<option value="nl">Dutch</option>
<option value="en">English</option>
</Field>
<button
type="button"
className="bg-gradient-to-b"
onClick={(e) => {
addLanguageValue(values);
}}
>
Add language
</button>
</div>
<div>
<FieldArray
name="questions"
render={(rootHelper) => (
<div>
{values.questions.map((value, j) => {
return <div>{value}</div>;
})}
</div>
)}
/>
</div>
</Form>
)}
</Formik>
You're mutating the state object, which causes the problem. If you create a fresh object in addLanguageValue, it works as expected:
function addLanguageValue() {
setQuestionnaire({
...questionnaire,
questions: [...questionnaire.questions, questionnaire.selectedLanguage]
});
}
Sandbox example
Because the onClick function doesn't cause a re-render of the state, you can use the following work around / trick by using an inoffensive function as setStatus to trigger re-render:
<button
type='button'
className='bg-gradient-to-b'
onClick={e => {
addLanguageValue(values);
//Used for rerendering.
props.setStatus('Adding language!');
}}
>
Add language
</button>;

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 app showing form in dialog results in a "findDOMNode is deprecated" error

I have a react app, the parent component has a button which when clicked shows a simple dialog with one text input and a submit button. Strict mode is enabled. There are two issues
The form input is set to show an initial value (formik initialValues is set) in the input but that is not being set
When the button is clicked I see an error in the console;
Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Transition which is inside StrictMode. Instead, add a ref directly to the element you want to reference.
The dialog component comes from Material UI and the form comes from Formik. I've created a simple repro here. The error is in the dev tools console. What would cause that error and why is the value not initialising?
Here's the parent component;
import React, { useState } from "react";
import { Button, Typography } from "#material-ui/core";
import ProfileEditor from "./ProfileEditor";
function ProfileManager() {
const [open, setOpen] = useState(false);
const handleClose = () => {
setOpen(false);
};
const handleOpen = () => {
setOpen(true);
};
return (
<div>
<Typography variant="h5">Profile Manager</Typography>
<Button variant="outlined" color="primary" onClick={handleOpen}>
Open profile editor dialog
</Button>
<ProfileEditor open={open} onClose={handleClose}></ProfileEditor>
</div>
);
}
export default ProfileManager;
and the dialog component displayed when the button is clicked in the component above;
import React from "react";
import {
Button,
Dialog,
DialogContent,
LinearProgress,
TextField
} from "#material-ui/core";
import { Formik, Form } from "formik";
interface Props {
open: boolean;
onClose: () => void;
}
function ProfileEditor(props: Props) {
return (
<Dialog open={props.open}>
<DialogContent>
<Formik
// initial value not being displayed !!! 😢
initialValues={{
firstName: "Billy"
}}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
setSubmitting(false);
alert(JSON.stringify(values, null, 2));
}, 500);
}}
>
{({ submitForm, isSubmitting }) => (
<Form>
<TextField name="firstName" type="text" label="First name" />
{isSubmitting && <LinearProgress />}
<br />
<Button
variant="contained"
color="primary"
disabled={isSubmitting}
onClick={submitForm}
>
Submit
</Button>
<Button variant="contained" onClick={props.onClose}>
Close
</Button>
</Form>
)}
</Formik>
</DialogContent>
</Dialog>
);
}
export default ProfileEditor;
You need to include a value prop to the form field to have it initialized properly.
{({ submitForm, isSubmitting, values }) => (
<Form>
<TextField
name="firstName"
type="text"
label="First name"
value={values.firstName} /* you need this prop */
/>
...
CodeSandBox: https://codesandbox.io/s/so-react-formik-inside-material-dialog-sfq4e?file=/ProfileEditor.tsx
Regarding your issue on the console, I'm not entirely sure at this point what is causing it, but if it bothers you or is causing additional problems, perhaps you can opt to move out of strict mode
<React.Fragment>
<ProfileManager></ProfileManager>
</React.Fragment>

Unable to retrieve the input field of material UI using refs in react js

I am developing a Web application using React JS + Material UI core. Now, I am building a form with the material ui control. Now, I am trying to retrieve the input field value (TextField) using refs of React. It is always saying undefined.
This is my component
class CreateEventComponent extends React.Component{
constructor(props)
{
super(props)
}
submitCreateEventForm(e)
{
e.preventDefault();
alert(this.refs.name.input.value)
}
render()
{
return (
<MuiThemeProvider>
<div className={scss['page-container']}>
<Grid
spacing={16}
container>
<Grid item md={12}>
<Card>
<CardContent>
<form onSubmit={this.submitCreateEventForm.bind(this)}>
<div>
<TextField
ref="name"
className={scss['form-control']}
name="name"
label="Name" />
</div>
<div>
<Grid>
<Button type="submit" color="primary" variant="raised">Save</Button>
</Grid>
</div>
</form>
</CardContent>
</Card>
</Grid>
</Grid>
</div>
</MuiThemeProvider>
)
}
}
function mapStateToProps(state)
{
return {
};
}
function matchDispatchToProps(dispatch)
{
return bindActionCreators({
}, dispatch);
}
const enhance = compose(withWidth(), withStyles(themeStyles, { withTheme: true }), connect(mapStateToProps, matchDispatchToProps))
export default enhance(CreateEventComponent);
As you can see, when form submits, I am trying to alert the name input field using refs. But it is always showing "undefined". I tried using this to fetch the value of TextField.
alert(this.refs.name.value)
It throws error saying name is undefined. So, how can I fetch the value of TextField using Ref?
I used this way as well.
I create ref in the constructor
constructor(props)
{
super(props)
this.nameRef = React.createRef();
}
Then set the ref for the TextField
<TextField
ref={this.nameRef}
className={scss['form-control']}
name="name"
label="Name" />
Then retrieve the values in this ways.
this.nameRef.value
this.nameRef.input.value
It is giving me the same error as well.
Original Answer
You need to create a ref in your constructor.
From the docs:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); // create a ref
}
render() {
return <div ref={this.myRef} />;
}
}
Updated Answer
According to Material UI's documentation, you need to pass in a callback to the inputRef prop on your <TextField />.
So, in addition to the original answer, try this as well:
<TextField
inputRef={e => this.nameRef = e}
className={scss['form-control']}
name="name"
label="Name" />
if you are using a stateless functional component with material ui then you can use react hooks.
import React, { useState, useRef } from "react";
let MyComponent = (props) => {
let textInput = useRef(null);
return (
<div>
<Button
onClick={() => {
setTimeout(() => {
textInput.current.focus();
textInput.current.click();
textInput.current.value="myname";
console.log(textInput.current.value);
}, 100);
}}
>
Focus TextField
</Button>
<TextField
fullWidth
required
inputRef={textInput}
name="firstName"
type="text"
placeholder="Enter Your First Name"
label="First Name"
/>
</div>
);
};
For me, this solves the problem:
<TextField
ref={this.nameRef}
onChange={e => {
this.nameRef.current.value = e.target.value;
}}
className={scss['form-control']}
name="name"
label="Name" />

Resources