ReactJS and autofocus - javascript

I have a react-bootstrap modal with an <input>. I want to set the autofocus attribute on the <input>
The following works fine, but shows a warning in the console
<input type="text" autofocus='true' />
Warning: Invalid DOM property `autofocus`. Did you mean `autoFocus`?
The following options do not work, in the sense that they do not focus the input when opening the modal:
<input type="text" autoFocus='true' />
<input type="text" autoFocus={true} />
<input type="text" autoFocus />
What is the recommended way of setting autofocus. Or how should I mute the warnings for the example that works well?
Note: This is react 16.8.6

If you're using React Hooks, add useCallback() to your component and add a ref={callback} to the form control:
import React, { useCallback } from 'react'
function InputComponent() {
const autoFocus = useCallback(el => el ? el.focus() : null, [])
return <input type="text" ref={autoFocus} />
}
export default InputComponent
You can replace the <input> with a React Bootstrap FormControl too.

Refs is what you want,
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount(){
this.myRef.current.focus();
}
<input type="text" ref={this.myRef} />

If you are using react hooks, you could write your own simple auto focus hook:
import { useEffect, useState } from "react";
export const useAutoFocus = (inputId: string) => {
const [initialized, setInitialized] = useState(false);
useEffect(() => {
if(!initialized) {
document.getElementById("email").focus();
setInitialized(true);
}
});
};
and the simply use e.g.
useAutoFocus("email")
in your form.

Related

Setting mobX state from inside a React-Apollo component

When trying to set the onChange state of an input element, I am unable to change the state. React-Apollo components need a child function that returns some JSX. Inside the child function It appears that the thisobject is being inherited, but I cant get it to actually change.
If I remove the <Mutation/> component all together then everything works as expected. Is there something special about React-Apollo components or the way the this object interacts with arrow functions?
import React from 'react';
import gql from 'graphql-tag'
import { Mutation } from 'react-apollo';
import { extendObservable } from 'mobx';
import { observer } from 'mobx-react';
const mutation = gql`here is a mutation`
class Why extends React.Component{
constructor(props) {
super(props);
extendObservable(this, {
text: '',
})
}
onChange = e => {
this.text = e.target.value;
};
render () {
return (
<Mutation mutation={mutation}>
{ () => (
<div>
{console.log(this)}
<input name="text"
placeholder="Enter Text"
type="text"
value={this.text}
onChange={this.onChange}/>
</div>
)
}
</Mutation>
)
}
}
export default observer(Why);
I think the state is actually changing but the component render didn't react for you.
It happens because observer components only tracks data that directly accessed by the render function, in your case you have a function that don't.
a simple solution is to use the <Observer /> component from mobx-react:
render () {
return (
<Mutation mutation={mutation}>
{ () => (
<Observer>
{() => (
<div>
{console.log(this)}
<input name="text"
placeholder="Enter Text"
type="text"
value={this.text}
onChange={this.onChange}/>
</div>
)}
</Observer>
)
}
</Mutation>
)
}

React / Redux with AntDesign focus on component

I'm kind stuck on this feature that i have do implement on my app. I need to set focus in a component on componentDidMount() or something similar.
i'm already try some suggestions like:
componentDidMount(){
this.nameDiv.focus();
}
<div ref={(div) => { this.nameDiv = div; }}>
for focus or similar for (Antdesign component) focus.
or something like that:
document.getElementById("mytext").focus();
<input type="text" id="mytext"/>
usualy i'm receiveing errors on my console: "Cannot read property 'focus' of undefined"
So the question: How can i set focus on a react / antDesign component?
Please look to following code. I'm sure this would help you.
import React from "react";
import ReactDOM from "react-dom";
class TestFocus extends React.Component {
componentDidMount = () => {
this.refs.focusedInput.focus();
};
render = () =>
<React.Fragment>
<input placeholder="I don't want focus :/" />
<br />
<input ref="focusedInput" placeholder="Please focus on me :B" />
</React.Fragment>;
}
ReactDOM.render(<TestFocus />, document.getElementById("root"));
Tested with react 16.8.6 & react-dom 16.8.6
Let me know, if this helps.

Redux form props & typescript

Was looking for years, didn't find anything worthy tho.
When I was working with flow, I could simply:
import { type FieldProps, FormProps } from 'redux-form';
Is there a similar (and that easy) way to properly set props to redux form in typescript?
Docs aren't saying anything about typescript, there's only a page for Flow typings.
However, I found that I can import something like propTypes from redux-form:
import { reduxForm, propTypes } from 'redux-form'
However - redux-form has nothing like propTypes exported, so docs are kinda deprecated.
Link: https://redux-form.com/7.2.1/docs/api/props.md/
Thanks in advance for any kind of help.
tl;dr class RegistrationForm extends React.PureComponent<any> {
what to drop here ^^^^^
You need to install the #types/redux-form package with your package manager. The #types/redux-form package includes types definitions for redux-form package.
Then you can import type definitions from redux-form, for example InjectedFormProps.
Your form that will be wrapped with reduxForm() should has props that extends InjectedFormProps<FormData = {}, P = {}>.
reduxForm() type is generic reduxForm<FormData = {}, P = {}>(...
See the example:
import * as React from 'react';
import { reduxForm, InjectedFormProps, Field } from 'redux-form';
import { IUser } from './index';
interface IProps {
message: string;
}
class UserForm extends React.Component<InjectedFormProps<IUser, IProps> & IProps> {
render() {
const { pristine, submitting, reset, handleSubmit, message } = this.props;
return (
<form onSubmit={handleSubmit}>
<div>{message}</div>
<div>
<label>First Name </label>
<Field
name="firstName"
component="input"
type="text"
placeholder="First Name"
/>
</div>
<div>
<label>Last Name </label>
<Field
name="lastName"
component="input"
type="text"
placeholder="Last Name"
/>
</div>
<div>
<button type="submit" disabled={pristine || submitting}>
Submit
</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>
Clear Values
</button>
</div>
</form>
);
}
}
export default reduxForm<IUser, IProps>({
form: 'userForm',
})(UserForm);
The source code of #types/redux-form package is located here. You can see the types there and more complicated examples in the redux-form-tests.tsx file that is used for types checking.

Uncaught TypeError: this.props.xxx is not a function in React

I'm using React.js for a project and I'm getting some troubles. Here is my problem:
I have this component which is for creating a new recipe:
import React, {Component, PropTypes} from 'react';
import { reduxForm } from 'redux-form';
import {Link} from 'react-router';
import { createRecipe } from '../actions/index';
class NewRecipe extends Component {
static contextTypes = {
router:PropTypes.object
};
onSubmit(props){
this.props.createRecipe(props).then(() => {
this.context.router.push('/yourRecipes');
});
}
render(){
const name = this.props.fields.name;
const description = this.props.fields.description;
const handleSubmit = this.props.handleSubmit;
return(
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<h3>New recipe</h3>
<div>
<label>Name</label>
<input type="text" className="form-control" {...name} />
</div>
<div>
<label>Description</label>
<input type="text" className="form-control" {...description} />
</div>
<button type="submit" className="btn btn-primary btn-primary-spacing">Submit</button>
<Link to="/yourRecipes" className="btn btn-danger btn-primary-spacing">Cancel</Link>
</form>
);
}
}
export default reduxForm({
form: 'NewRecipeForm',
fields: ['name','description']
}, null, { createRecipe })(NewRecipe);
createRecipe action creator looks like this inside index.js file:
export function createRecipe(props){
const request = axios.post('http://localhost:3001/recipes/new', props);
return {
type: CREATE_RECIPE,
payload: request
};
}
Everytime I try to click the submit button of the form I get this error in the browser console:
Uncaught TypeError: this.props.createRecipe is not a function
The error is because there is not such function defined in this react class and you are trying to access it using this.props.createRecipe.
One way is you would directly call as createRecipe() as you have the import.
One more way is you use connect from react-redux and connect this class with the state and dispatch props and then you can use this.props.createRecipe()
If you are using redux-form 6.x.x then you need to make use of connect
NewRecipe = reduxForm({
form: 'NewRecipeForm',
fields: ['name','description']
}, null)(NewRecipe);
export default(null, createRecipe)(NewRecipe);

input form sending blank value in reactjs

i am trying to console.log the input value using react. below is the code i have written
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component{
constructor() {
super();
this.processHand = this.processHand.bind(this);
}
processHand(e){
e.preventDefault();
const handMoneyReceived = this.handMoney.value;
console.log(handMoneyReceived);
}
render(){
return(
<div>
<form onSubmit = {this.processHand}>
<input type="text"/>
<input type="submit" ref= {ref => this.handMoney = ref}/>
</form>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('container'));
the console.log(handMoneyReceived) is logging out blank value instead of value entered on the form.
Because you used ref on wrong field, use it with text field, try this:
<input type="text" ref= {ref => this.handMoney = ref}/>
Check the working fiddle: https://jsfiddle.net/mayankshukla5031/k1efLh8e/

Categories

Resources