React input defaultValue focus and select - select

I have a component with an input-element, i use defaultValue to set the initial value.
I want to focus that element and select the whole value initially, but it seems that the defaultvalue is not set when componentDidMount is called.
Do you have any tips?
i use window.setTimeout but i want to avoid that in my react-components:
public componentDidMount(): void {
if (this.props.focus) {
let tInput: HTMLInputElement = ReactDOM.findDOMNode(this).getElementsByTagName("input").item(0);
if (tInput) {
tInput.focus();
// FixMe: defaultValue is set too late by react so i cant set selection instantly
if (this.props.defaultValue) {
window.setTimeout(
() => {tInput.setSelectionRange(0, this.props.defaultValue.length); },
100
);
}
}
}
}

Works fine for me:
class MyComponent extends React.Component {
componentDidMount () {
const { myInput } = this.refs
myInput.focus()
myInput.select()
}
render () {
return (
<input type='text' defaultValue='Foobar' ref='myInput' />
)
}
}
I wouldn't use any reactDOM methods other than render/renderToString. These apis are "escape hatches" and usage is not recommended.

Related

How can I use props to auto-populate editable redux-form fields in React?

I'm new to React so I've tried to show as much code as possible here to hopefully figure this out! Basically I just want to fill form fields with properties from an object that I fetched from another API. The object is stored in the autoFill reducer. For example, I would like to fill an input with autoFill.volumeInfo.title, where the user can change the value before submitting if they want.
I used mapDispatchtoProps from the autoFill action creator, but this.props.autoFill is still appearing as undefined in the FillForm component. I'm also confused about how to then use props again to submit the form. Thanks!
My reducer:
import { AUTO_FILL } from '../actions/index';
export default function(state = null, action) {
switch(action.type) {
case AUTO_FILL:
return action.payload;
}
return state;
}
Action creator:
export const AUTO_FILL = 'AUTO_FILL';
export function autoFill(data) {
return {
type: AUTO_FILL,
payload: data
}
}
Calling the autoFill action creator:
class SelectBook extends Component {
render() {
return (
....
<button
className="btn btn-primary"
onClick={() => this.props.autoFill(this.props.result)}>
Next
</button>
);
}
}
....
function mapDispatchToProps(dispatch) {
return bindActionCreators({ autoFill }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(SelectBook);
And here is the actual Form where the issues lie:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import { createBook } from '../actions/index;
class FillForm extends Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
}
onSubmit(props) {
this.props.createBook(props)
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
const { fields: { title }, handleSubmit } = this.props;
return (
<form {...initialValues} onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<input type="text" className="form-control" name="title" {...title} />
<button type="submit">Submit</button>
</form>
)
}
export default reduxForm({
form: 'AutoForm',
fields: ['title']
},
state => ({
initialValues: {
title: state.autoFill.volumeInfo.title
}
}), {createBook})(FillForm)
I think you're mixing up connect and reduxForm decorators in the actual form component. Currently your code looks like this (annotations added by me):
export default reduxForm({
// redux form options
form: 'AutoForm',
fields: ['title']
},
// is this supposed to be mapStateToProps?
state => ({
initialValues: {
title: state.autoFill.volumeInfo.title
}
}),
/// and is this mapDispatchToProps?
{createBook})(FillForm)
If this is the case, then the fix should be as simple as using the connect decorator as it should be (I also recommend separating this connect props to their own variables to minimize confusions like this):
const mapStateToProps = state => ({
initialValues: {
title: state.autoFill.volumeInfo.title
}
})
const mapDispatchToProps = { createBook }
export default connect(mapStateToProps, mapDispatchToProps)(
reduxForm({ form: 'AutoForm', fields: ['title'] })(FillForm)
)
Hope this helps!

How to use node-simple-schema reactively?

Given that there is not much examples about this, I am following the docs as best as I can, but the validation is not reactive.
I declare a schema :
import { Tracker } from 'meteor/tracker';
import SimpleSchema from 'simpl-schema';
export const modelSchema = new SimpleSchema({
foo: {
type: String,
custom() {
setTimeout(() => {
this.addValidationErrors([{ name: 'foo', type: 'notUnique' }]);
}, 100); // simulate async
return false;
}
}
}, {
tracker: Tracker
});
then I use this schema in my component :
export default class InventoryItemForm extends TrackerReact(Component) {
constructor(props) {
super(props);
this.validation = modelSchema.newContext();
this.state = {
isValid: this.validation.isValid()
};
}
...
render() {
...
const errors = this.validation._validationErrors;
return (
...
)
}
}
So, whenever I try to validate foo, the asynchronous' custom function is called, and the proper addValidationErrors function is called, but the component is never re-rendered when this.validation.isValid() is supposed to be false.
What am I missing?
There are actually two errors in your code. Firstly this.addValidationErrors cannot be used asynchronously inside custom validation, as it does not refer to the correct validation context. Secondly, TrackerReact only registers reactive data sources (such as .isValid) inside the render function, so it's not sufficient to only access _validationErrors in it. Thus to get it working you need to use a named validation context, and call isValid in the render function (or some other function called by it) like this:
in the validation
custom() {
setTimeout(() => {
modelSchema.namedContext().addValidationErrors([
{ name: 'foo', type: 'notUnique' }
]);
}, 100);
}
the component
export default class InventoryItemForm extends TrackerReact(Component) {
constructor(props) {
super(props);
this.validation = modelSchema.namedContext();
}
render() {
let errors = [];
if (!this.validation.isValid()) {
errors = this.validation._validationErrors;
}
return (
...
)
}
}
See more about asynchronous validation here.

material-ui textfield with japanese

Excuse my poor English.
'TextField' of material-ui have problem with japanese input.
when use it inside 'Dialog' tag.
First letter is determined without consideration.
for example, entering 'da' should be 'だ', 'pa' should be 'ぱ'.
but it become 'dあ' and 'pあ' because first letter is determined automatically.
when first letter is entered, it should be suspended
until second letter inputted.
does anyone have idea?
import React, { Component } from 'react';
import Dialog from 'material-ui/Dialog';
import TextField from 'material-ui/TextField';
export default class MyModal extends Component {
constructor(props) {
super(props);
this.state = {
question: '',
};
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(event) {
this.setState({
question: event.target.value,
});
}
render() {
return (
<Dialog
open
>
<TextField
value={this.state.question}
onChange={this.onInputChange}
/>
</Dialog>
);
}
}
I think it's a material-ui bug. I found 2 solutions to work around it.
1: Don't put value state of TextField in Dialog. You should write like below:
class MyForm extends Component {
constructor(props) {
super(props);
this.state = {
question: '',
};
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(event) {
this.setState({
question: event.target.value,
});
}
render() {
return (
<TextField
value={this.state.question}
onChange={this.onInputChange}
/>
);
}
}
export default class MyModal extends Component {
render() {
return (
<Dialog
open
>
<MyForm />
</Dialog>
);
}
}
2; Or you can extend material-ui TextField with a little fix. This way is pretty dangerous. But it works fine for me now. (I'm using material-ui 0.15.4)
export default class FixedTextField extends mui.TextField {
handleInputChange = (event) => {
if (this.props.onChange) this.props.onChange(event, event.target.value);
}
}

Handling tab for lists in Draft.js

I have a wrapper around the Editor provided by Draft.js, and I would like to get the tab/shift-tab keys working like they should for the UL and OL. I have the following methods defined:
_onChange(editorState) {
this.setState({editorState});
if (this.props.onChange) {
this.props.onChange(
new CustomEvent('chimpeditor_update',
{
detail: stateToHTML(editorState.getCurrentContent())
})
);
}
}
_onTab(event) {
console.log('onTab');
this._onChange(RichUtils.onTab(event, this.state.editorState, 6));
}
Here I have a method, _onTab, which is connected to the Editor.onTab, where I call RichUtil.onTab(), which I assume returns the updated EditorState, which I then pass to a generic method that updates the EditorState and calls some callbacks. But, when I hit tab or shift-tab, nothing happens at all.
So this came up while implementing with React Hooks, and a google search had this answer as the #2 result.
I believe the code OP has is correct, and I was seeing "nothing happening" as well. The problem turned out to be not including the Draft.css styles.
import 'draft-js/dist/Draft.css'
import { Editor, RichUtils, getDefaultKeyBinding } from 'draft-js'
handleEditorChange = editorState => this.setState({ editorState })
handleKeyBindings = e => {
const { editorState } = this.state
if (e.keyCode === 9) {
const newEditorState = RichUtils.onTab(e, editorState, 6 /* maxDepth */)
if (newEditorState !== editorState) {
this.handleEditorChange(newEditorState)
}
return
}
return getDefaultKeyBinding(e)
}
render() {
return <Editor onTab={this.handleKeyBindings} />
}
The following example will inject \t into the current location, and update the state accordingly.
function custKeyBindingFn(event) {
if (event.keyCode === 9) {
let newContentState = Modifier.replaceText(
editorState.getCurrentContent(),
editorState.getSelection(),
'\t'
);
setEditorState(EditorState.push(editorState, newContentState, 'insert-characters'));
event.preventDefault(); // For good measure. (?)
return null;
}
return getDefaultKeyBinding(event);
}

React, get bound parent dom element name within component

Within my component, how can I access the name of the parent component it is nested inside?
So if my render is thus:
ReactDOM.render(
<RadialsDisplay data={imagedata}/>,
document.getElementById('radials-1')
);
How can I retrieve the id name #radials-1 from within the component itself?
It probably makes the most sense to pass it as a property, but if you really need to get it programmatically, and from inside the component, you can wait for the component to mount, find its DOM node, and then look at its parent.
Here's an example:
class Application extends React.Component {
constructor() {
super();
this.state = { containerId: "" };
}
componentDidMount() {
this.setState({
containerId: ReactDOM.findDOMNode(this).parentNode.getAttribute("id")
});
}
render() {
return <div>My container's ID is: {this.state.containerId}</div>;
}
}
ReactDOM.render(<Application />, document.getElementById("react-app-container"));
Working demo: https://jsbin.com/yayepa/1/edit?html,js,output
If you do this a lot, or want to be really fancy, you could utilize a higher-order component:
class ContainerIdDetector extends React.Component {
constructor() {
super();
this.state = { containerId: "" };
}
componentDidMount() {
this.setState({
containerId: ReactDOM.findDOMNode(this).parentNode.getAttribute("id")
});
}
render() {
if (!this.state.containerId) {
return <span />;
} else {
return React.cloneElement(
React.Children.only(this.props.children),
{ [this.props.property]: this.state.containerId }
);
}
}
}
ContainerIdDetector.propTypes = {
property: React.PropTypes.string.isRequired
}
// Takes an optional property name `property` and returns a function. This
// returned function takes a component class and returns a new one
// that, when rendered, automatically receives the ID of its parent
// DOM node on the property identified by `property`.
function withContainerId(property = "containerId") {
return (Component) => (props) =>
<ContainerIdDetector property={property}>
<Component {...props} />
</ContainerIdDetector>
}
Here, withContainerId is a function that takes an argument called property and returns a new function. This function can take a component type as its only argument, and returns a higher-order component. When rendered, the new component will render the passed component, with all its original props, plus an additional prop specifying the parent container's ID on the property specified by the property argument.
You can use them with ES7 decorators (as currently implemented) if you wish, or via a regular function call:
#withContainerId()
class Application extends React.Component {
render() {
return <div>My containers ID is: {this.props.containerId}</div>;
}
}
// or, if you don't use decorators:
//
// Application = withContainerId()(Application);
ReactDOM.render(<Application />, document.getElementById("react-app-container"));
Working demo: https://jsbin.com/zozumi/edit?html,js,output