unable to save the input of the value - reactjs

I'm new to reactjs, unable to import body object in another component?
Could you please help me in importing the body object in the compose component. I'm unable to display the content of the body.

As you have provided value and onChange here,
<Editor label='Body' name="body" value={this.state.body} onChange={this.changeHandler}/>
But in Editor component you have not provided value and onChange to ReactQuill, you should do this,
<ReactQuill
theme='snow'
modules={this.modules}
formats={this.formats}
className='Editor'
value={this.props.value} // provide value passed as props from parent component
onChange={this.props.onChange} // provide onChange passed as props from parent component
/>
Note: I think you should have separate change handler for your Editor component, because ReactQuill directly provides value on change.
<Editor label='Body' name="body" value={this.state.body} onChange={this.changeBodyHandler}/>
And the handler should be this,
changeBodyHandler = (value) => {
this.setState({
body: value
})
}
Simplified Demo

You can try this:
changeBodyHandler = (e) => {
this.setState({
body: e.target.value
})
}

Related

How to handle Formik's `handleChange` prop?

I get it that Field has an onChange attribute where you can pass the own Formik onChange prop from here: https://jaredpalmer.com/formik/docs/api/formik#handlechange-e-reactchangeevent-any-void.
However, I am struggling to understand where these value[key] is passed, so I can handle the data passed in the form. Found in withFormik(): How to use handleChange that I can pass two callbacks to Formik's onChange prop, but I wonder if there is a better way to handle this.
edit after comments from folks that replied, thanks for that:
My code using these 2 callbacks in the onChange prop in Field:
export default function FormikForm() {
const onSubmitHandler = (formValues, actions) => {
console.log(formValues);
console.log(actions);
};
const onChangeHandler = (e) => {
console.log(e.target.value);
};
return (
<div>
<h1>This is the Formik Form</h1>
<Formik
initialValues={{
name: "",
email: "",
age: ""
}}
onSubmit={onSubmitHandler}
render={props => {
return (
<Form>
<label>
Name
<Field
name="name"
type="text"
placeholder="name"
onChange={e => {props.handleChange(e); onChangeHandler(e)}}
/>
</label>
<button type="submit">Submit</button>
</Form>
);
}}
/>
</div>
);
}
Is there a way to do a similar thing as in onSubmitHandler, where Formik automagically outputs the value of the input without having to call these 2 functions in the onChange?
Thanks
Every field component receives a field prop which has a value prop containing the value for that field, as well as a form prop containing helper methods that you can use to set the value. I'd need to see the structure of your code to give specific suggestions on how to implement what you want, but you can emulate the default functionality by calling form.setFieldValue(field.name, field.value). In addition, the field prop has this handler built in by default in the field.onChange prop.

Updating parents props via child's state <Field> Component

I have a Field Component (redux-form) that calls a custom ImageInput component that uploads an image, then spits out the src.
I need to pass that src from my child component, to the parent where it updates the parents state via a handler.
I've tried to follow this answer, but am a bit confused as my setup seems a little different: How to update parent's state in React?
Here is my parent component
handleChange(e) {
console.log(e)
this.setState({[e.target.name]: e.target.value});
}
<Field
{...this.props}
component={ImageInput}
name="templating.img"
onChange={this.handleChange.bind(this)}
/>
and then my child where the image is inputted and uploaded
constructor(props) {
console.log('props', props);
super(props);
this.state = {
src: null
}
console.log(this.state)
}
_imgUpload = (e) => {
e.preventDefault();
// console.log(e.target.files)
if (e.target.files.length === 1) {
let file = e.target.files[0]
loadImage(e.target.files[0])
.then(uploadThumbor)
.then(formatImage)
.then(({src, dataUri}) => {
this.setState({src: src})
console.log('img', src)
})
}
}
/* Snippet where the image upload occurs */
<div style={styles.image}>
<div style={styles.defaultPreview}></div>
<div style={styles.sample}></div>
<input type="file" style={styles.uploadPreview} accept="image/*" onChange={this._imgUpload} />
</div>
After an image has been upload, I am setting the state in the child component. I need to pass that state to the parent where it'll update it's state. I dont think the onChange={this.handleChange.bind(this)} is correct for this parent component in this instance (it is correct for other Field components that are simple inputs).
Any help would be awesome.
I get what you are trying to do.
You said that you are using redux form. Is this the only input in the form? Why is it uploading the image separately as soon as it changes?
I ask this cause the call to the api is normally dispatched form the parent container. If this api call is specific to this page I would suggest moving it to the parent and maintain the src state in the parent. If you need it here you can always pass it down as prop.
If this is not an option you can always have a separate callback function similar to the handleOnChange. It would be called when you get the new src from the backend. This will allow you to maintain the src in the parent state as you wanted. In this case, if you need to have the src in the input component you can do the same as in the other solution, pass it down as a prop.
Parent
handleChange(e) {
console.log(e)
this.setState({[e.target.name]: e.target.value});
}
handleSrcChange(src) {
this.setState({ imageSrc: src });
}
<Field
{...this.props}
component={ImageInput}
name="templating.img"
onChange={this.handleChange.bind(this)}
onSrcChange={this.handleSrcChange.bind(this)}
/>
Input Component
_imgUpload = (e) => {
e.preventDefault();
// console.log(e.target.files)
if (e.target.files.length === 1) {
let file = e.target.files[0]
loadImage(e.target.files[0])
.then(uploadThumbor)
.then(formatImage)
.then(({src, dataUri}) => {
this.props.onSrcChange(src);
console.log('img', src)
})
}
}
/* Snippet where the image upload occurs */
<div style={styles.image}>
<div style={styles.defaultPreview}></div>
<div style={styles.sample}></div>
<input type="file" style={styles.uploadPreview} accept="image/*" onChange={this._imgUpload} />
</div>

Redux Form wrapper for kendo-react-ui Input error

I am using react-kendo-ui. I want to wrap Input from #progress/kendo-react-inputs to use it with ReduxForm. Please find my code below:
import React from 'react'
import { Input } from '#progress/kendo-react-inputs';
const InputText = ({ input, label, type, meta: { touched, error } }) => (
<div>
<label>{label}</label>
<div>
<Input {...input} type={type} placeholder={label} />
{touched && error && <span>{error}</span>}
</div>
</div>
)
export default InputText
Call the InputText from another component as below:
import React from 'react';
import { Field, reduxForm } from 'redux-form';
import { Input } from '#progress/kendo-react-inputs';
import InputText from './input-text';
const validateNotEmpty = value => !value ? 'Must enter a value' : null;
const onSubmit = (values) => {
console.log(values);
}
const AddLoc= ({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<div>
<Field
label="Address"
name="address"
component={InputText}
validate={validateNotEmpty}
/>
</div>
<button type="submit">Submit</button>
</form>
)
export default reduxForm({
form: 'AddLoc'
})(AddLoc)
But while typing inside the input text it keeps giving the following error/warning:
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property `nativeEvent` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().
While typing inside the input text automatically outputs [object Object]. Please check the image above. Could anyone please let me know what is causing the error.
Thanks
The reduxForm works only with pure DOM <input />. Internally it clones the elements search the children and then attaches the onChange dynamically. So it will not work with the Input and the NumericTextBox from the #progress/kendo-react-inputs package. This statement is based on the official kendo documentation about integrating with the redux-form.
The same author of the redux-form have fork of it called react-final-form which could be used on any component that have Value and onChange props. By our tests it works with the components from #progress/kendo-react-inputs and #progress/kendo-react-dropdowns packages. It looks kendo already have an example using final-form in their integration section.

Selecting an element in React in a stateless function component in React?

<TextField
onChange={props.onChangeTextField}
ref="questionInput"
style={styles.textField}
value={props.existingValue}
fullWidth={true}
/>
I was trying to give an input field in a stateless function component to be able to focus it when the component loads like this:
componentWillMount = () => {
this.refs.questionInput.focus();
console.log('test')
}
}
But I got the error:
Stateless function components cannot have refs.
So is there a way to focus an input field in React without a ref?
You should wrap your input component with forwardRef function. Something like this:
import * as React from "react";
const TextInput = React.forwardRef(
(props, ref) => <input ref={ref} {...props} />
);
export default TextInput;
Note that it will add a second argument to your functional component, which you should pass to the DOM element as ref prop.
Yes. However your method of using ref is really outdated. You should update to the latest version of React (currently 16.3.2) and follow the official documentation
function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it
let textInput = React.createRef();
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input
type="text"
ref={textInput} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
No, you need to change the functional component into a class.
You may not use the ref attribute on functional components because they don’t have instances
You should also use the newer callback API to set the ref:
ref={ref => { this.questionInput = ref }}
Or createRef for v16.3.
Adding the autoFocus prop to the input component might do the trick if you just want it to be focused on mount:
<TextField autoFocus ..restOfProps />

react bootstrap readonly input within formcontrol

I am using react bootstrap and this framework provides some nice FormControls.
But I would like to make the Input field that is generated within the FormControls to have a prop of readonly="readonly". This way, this field looks the same as my other FormControls, but does not give a keyboard input on IOS.
In my case, the input will be provided by a calendar picker which will be triggered by an popover.
Does anyone know how to give FormControl the parameter readonly="readonly", so that the generated Input field in the browser will have the prop readonly="readonly"?
Many thnx for the answers!
It doesn't look like a problem with react-bootstrap, but rather with react itself.
React is not transferring the 'readonly' prop to the generated (real) DOM element:
React-bootstrap create the following react virtual dom input:
Yet, react generated the following real DOM element, omitting the readonly attribute:
Maybe using 'disabled' could help in your case:
<FormControl
disabled
type="text"
placeholder="Enter text"
onChange={this.handleChange}
/>
For differences between readonly & disbabled see here:
https://stackoverflow.com/a/7730719/1415921
I have created an issue in React's github repo: #6783
UPDATE
After getting an answer in the above issue. You need to write it with camelcase: readOnly.
So it should be:
<FormControl
readOnly
type="text"
placeholder="Enter text"
onChange={this.handleChange}
/>
Old problem, new approach: Take advantage of onChange event to control if you'll call handleChange event or not. I defined editForm as a props value controlled by buttons, to see if i'm in view or edit mode.
Example:
<TextField
name="id"
label="ID
value={entityState.entity.Id || ""}
onChange={(a) => (props.formEdit ? handleChange(a) : "")}
/>
On the basis of values this attribut will be readOnly={!!value} to make input field disable to edit
class Input extends React.Component {
render () {
const { defaultValue, value, onChange } = this.props
const nothing = () => {}
return (
<input
type='text'
defaultValue={defaultValue}
value={value ? value.toUpperCase() : undefined}
readOnly={!!value}
onChange={value ? nothing : onChange}
/>
)
}
}
class App extends React.Component {
constructor () {
super ()
this.state = {
value: 'arr'
}
}
handleChange (e) {
const { target: { value }} = event
this.setState({ value })
}
render () {
const { value } = this.state
return (
<div>
<Input
onChange={this.handleChange.bind(this)}
defaultValue={'patata'}
/>
<Input
value={value}
/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('arr'))

Resources