ReactJS component textarea not updating on state change - html

I'm trying to write a note taking/organizing app and I've run into a frustrating bug.
Here's my component:
import React from 'react';
const Note = (props) => {
let textarea, noteForm;
if (props.note) {
return (
<div>
<button onClick={() => {
props.handleUpdateClick(props.selectedFolderId, props.selectedNoteId, textarea.value);
}}>
Update
</button>
<textarea
defaultValue={props.note.body}
ref={node => {textarea = node;}}
/>
</div>
);
} else {
return <div></div>;
}
};
export default Note;
As it currently stands, whenever I switch between notes and rerender the note component with new content from the note.body prop, the textarea does not change and retains the content from the previous note. I've tried using the value attribute instead of the defaultValue attribute for the text area which doe fix the problem of the text area content not changing when the component rerenders, but when I do that I'm longer able to type in the textarea field to update the note
Doe anyone know a way I can both allow for users to type in the text field to update the note as well as have the textarea content change when I render different notes?
Thank you

The problem is that setting the value to your prop will cause all re-renders of the component to use the same prop, so new text is obliterated. One solution is to preserve the text in the local state of the component. To simultaneously listen to prop changes, you can set the state when you receive new props.
const Note = React.createClass({
getInitialState() {
return {
text : this.props.note.body
}
},
componentWillReceiveProps: function(nextProps) {
if (typeof nextProps.note != 'undefined') {
this.setState({text: nextProps.note.body });
}
},
render() {
if (this.props.note) {
return (
<div>
<button onClick={(e) => {
// Fire a callback that re-renders the parent.
// render(this.textarea.value);
}}>
Update
</button>
<textarea
onChange={e => this.setState({ text : e.target.value })}
value={this.state.text}
ref={node => {this.textarea = node;}}
/>
</div>
);
} else {
return <div></div>;
}
}
});
https://jsfiddle.net/69z2wepo/96238/
If you are using redux, you could also fire an action on the change event of the input to trigger a re-render. You could preserve the input value in a reducer.

Because componentWillReceiveProps is now unsafe Max Sindwani's answer is now a little out date.
Try these steps:
convert your component to a class
now you can include the shouldComponentUpdate() lifecycle hook
create your event handler and pass it into onChange
in <textarea> you can swap out defaultValue attribute for value (just use event.preventDefault() in the handler so that a user can continue to update text if required)
import React from 'react';
export class Note extends React.Component {
constructor(props) {
super(props);
this.state={text: this.props.note.body}
}
shouldComponentUpdate(nextProps) {
if(nextProps.note.body !== this.state.text) {
this.setState({text: nextProps.note.body})
return true;
}
return false;
}
updateText = (event) => {
event.preventDefault();
this.setState({text: nextProps.note.body});
}
render() {
if (this.props.note) {
return (
<div>
<textarea
onChange={this.updateText}
value={this.state.text}
name={'display'}
/>
</div>
);
} else {
return <div></div>;
}
}});

Related

How can a function value is displayed in a HTML tag with a return value from addEventListerner click?

I am trying to build a calculator and want to print digits on the screen. I have not yet put the calculator algorithm, just only to print the digits on the screen.
const Keys = ({calcKeys})=>(<div className="display-keys">
<div className="screen"><handleClick></div>
{calcKeys.map((item)=>{
return <button className="display-keys">{item.key}</button>
})
}
class App extends React.Component { constructor(props) { super(props);
this.state={calcKeys:[{"key": "AC"},{"key": "CE"},{"key": "±"},{"key": "/"},{"key": "7"},{"key": "8"},{"key": "9"},{"key": "x"},{"key": "4"},{"key": "5"},{"key": "6"},{"key": "-"},{"key": "1"},{"key": "2"},{"key": "3"},{"key": "+"},{"key": "."},{"key": "0"}]};}
this.displayKeys = this.displayKeys.bind(this)];
const keyButton = document.querySelector('.display-keys');
handleClick() {
keyButton.addEventListener('click', (e) => {
return const keyPad = e.key;
});
}
render(){
return(
<div className="display-container">
<Keys calcKeys={this.state.calcKeys}/>
</div>
);
}
}
ReactDOM.render( <App />, document.getElementById("root"));
For this case, if you want to click on the button you don't need to add an addEventListener.
As you are using React, you can create a function to handle click.
If you want to handle a keypress on the keyboard, that's the case to use addEventListener.
I changed your code a bit in order to make it work as expected. I didn't add any logic to make the calculator work but clicking on any button will add it to state and display on "screen".
This is what I did:
// "Keys" Component receives the calcKeys and the handleClick function.
// It uses the handleClick function on the button onClick passing the current item key
const Keys = ({ calcKeys, handleClick }) => (
<div className="display-keys">
{calcKeys.map(item => (
<button onClick={() => handleClick(item.key)}>{item.key}</button>
))}
</div>
)
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
calcKeys: [{"key": "AC"},{"key": "CE"},{"key": "±"},{"key": "/"},{"key": "7"},{"key": "8"},{"key": "9"},{"key": "x"},{"key": "4"},{"key": "5"},{"key": "6"},{"key": "-"},{"key": "1"},{"key": "2"},{"key": "3"},{"key": "+"},{"key": "."},{"key": "0"}],
value: '',
};
this.handleClick = this.handleClick.bind(this)
}
// Here I just receive the key and add it to state.
// This is the place to add logic, check if the key is "AC" for example and clean the state, etc.
handleClick(key) {
const { value } = this.state
this.setState({ value: `${value}${key}` })
}
render() {
const { value } = this.state
return (
<div className="display-container">
<div className="screen">{value}</div>
<Keys calcKeys={this.state.calcKeys} handleClick={this.handleClick} />
</div>
);
}
}
You can test it in a working JSFiddle here

React-Redux is not rendering data correctly inside input/textarea box

I have the example below where (1) and (2) would display the value of "Some Text" instead of Data.preview but (3) would show up Data.preview value just fine. I understand that case (1) - based on this article (ReactJS component not rendering textarea with state variable) wouldn't work for react but why does case (2) return "Some Text" (I also tried value=) instead of Data.preview value like case (3). I do not want it to be a placeholder so it would be editable. Thanks
render(){
const { Data } = this.props
return (
{Data.preview} {*/this would return the value correctly*/}
(1) <textarea className="form-control" maxLength="50" rows="3">{ Data.preview || "Some Text" }</textarea>
(2) <textarea className="form-control" maxLength="50" rows="3" defaultValue={ Data.preview || "Some Text"}></textarea> {*/or use value = {}, either would return "Some Text" */}
(3) <textarea className="form-control" placeholder={Data.preview || "Some Text"} maxLength="50" rows="3"></textarea>{*/ this would return Data.preview value */}
)
}
The textarea can take the value property for showing its current value, and then use the onChange handler to update that value.
In this sample I added both the one with no value yet, and the one which has a default value.
An important note would be that a value cannot be null; it has to be either undefined or empty.
The answer here doesn't really involve redux, but rather a component state for editing the value. I hope this helps enough to use it, applying it to your code.
const { Component } = React;
class DataEntrySample extends Component {
constructor( props ) {
super();
this.state = {
data: props.value
};
this.updateData = this.updateData.bind(this);
}
updateData(e) {
this.setState({ data: e.target.value });
console.log('changed to :' + e.target.value );
}
render() {
return (
<textarea
value={this.state.data}
onChange={this.updateData}
placeholder={this.state.data || 'Enter your data'}>
</textarea>
);
}
}
const target = document.querySelector('#container');
ReactDOM.render( <div><DataEntrySample /><DataEntrySample value="Some text" /></div>, target );
<script id="react" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.js"></script>
<script id="react-dom" src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.js"></script>
<div id="container"></div>
If you really want to do it through defaultValue, you have a chance to do that as well (as long as you define an onChange handler that updates the value somewhere).
There is rather a caveat, namely, it will not update any changes from outside of it's view, unless it can define that it has really changed, and with defaultValue. So the following example would work, changing the props from outside would not work.
const { Component } = React;
class DataEntrySample extends Component {
constructor( props ) {
super();
this.state = {
data: props.value
};
this.updateData = this.updateData.bind(this);
}
updateData(e) {
this.setState({ data: e.target.value });
console.log('changed to :' + e.target.value );
}
render() {
return (
<textarea
onChange={this.updateData}
defaultValue={this.state.data || 'Enter your data'}>
</textarea>
);
}
}
class ParentEntry extends Component {
constructor() {
super();
this.updateProps = this.updateProps.bind(this);
this.state = {
value: 'initial text'
};
}
updateProps( value ) {
this.setState({ value });
}
render() {
const { value } = this.state;
console.log( 'render' );
return (
<div>
<h1>With default value</h1>
<DataEntrySample value={value} />
<br />
<button onClick={()=>this.updateProps('empty text')} type="button">
Will set text to empty text
</button>
</div>
);
}
}
const target = document.querySelector('#container');
ReactDOM.render( <ParentEntry />, target );
<script id="react" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.js"></script>
<script id="react-dom" src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.js"></script>
<div id="container"></div>
You need to learn a bit more about controller components https://reactjs.org/docs/forms.html
If you then decide that you really need uncontrolled components: https://reactjs.org/docs/uncontrolled-components.html

How to change JSON data through textboxes and buttons in a ReactJS?

I just started learning react.
Please see code in codepen link below.
When you press the edit button, the field in the table is changed to a textbox.
And that's what I want.
I wanna give Click on the edit button again.
How to replace the value of the data in JSON data?
Thanks so much for the help.
let UsersData = [
{Name: 'AAA',Last:"1111"},
{Name: 'BBBB',Last:"222"},
]
constructor(props) {
super(props)
this.state={
Editing:false,
}
this.toggleEditing = this.toggleEditing.bind(this)}
toggleEditing() {
let Editing = !this.state.Editing
this.setState(
{Editing: Editing}
)}
FULL CODE IN CODEPEN
Codepen https://codepen.io/StCrownClown/pen/MEQPzP?editors=0010
To change your JSON data first you need to get the user input through your TextInput component, to do that you need to define a value and an onChange props to store the value of the input in your state. Given that your input is a custom component I'll pass those props as props.
Like this:
class TextInput extends React.Component {
render() {
const {value, onChange, name} = this.props
return (
<td>
<input type="text"
value={value} // to display the value
onChange={onChange} // to store the value on the state
name={name} // to use use the name as a property of the state
/>
</td>
)
}
}
Then in your TableRow component state, you need to:
Save those value and handle their changes:
this.state = {
Editing:false,
// from props to show their current value
name : this.props.data.Name
last: this.props.data.Last
}
// to handle changes
onChange(event){
this.setState({
[event.target.name] : event.target.value
})
}
and pass the above mentioned props to the TextInput:
<TextInput value={this.state.name} name="name" onChange={this.onChange}></TextInput>
<TextInput value={this.state.last} name="last" onChange={this.onChange} ></TextInput>
To show those values to the user when to Editing is false you need to:
Defined a state for your Table component so it re-renders with the changes and a function that changes that state when the user is done editing:
this.state = {
UsersData: UsersData
}
saveChanges({key, name, last}){
// key: unique identifier to change the correct value in the array
// name: new Name
// last: new Last
this.setState(prevState => ({
UsersData: prevState.UsersData.map(data => {
if(data.Name === key) return { Name: name, Last: last }
return data
})
}))
}
Finally, pass that function to the TableRow component:
const rows = []
// now the loop is from the UsersData in the component state to see the changes
this.state.UsersData.forEach((data) => {
rows.push (
<TableRow
key={data.Name}
saveChanges={this.saveChanges}
data={data}
/>
)
})
and call the saveChanges function in the TableRow component when the Done button is clicked:
saveChanges(){
const {name , last} = this.state
this.toggleEditing()
this.props.saveChanges({
key: this.props.data.Name,
name,
last
})
}
<button onClick={this.saveChanges} >Done</button>
You can check the full code here.

Calling a function when opening a react-native screen

I'm trying to load a JSON from AsyncStorage every time a user opens one of my react-native screens (I'm using StackNavigator). This JSON contains information on what my states should be set to.
How can I call a function that runs every time this screen is opened?
Further info:
I've written a function that updates my states according to a JSON loaded from AsyncStorage. The function works perfectly when called from a button, but when the function is called from render(), part of my screen freezes and some buttons are not touchable anymore. Strangely only TextInput still works.
use componentWillMount() method. This will execute automatically before render() method gets triggered.
class Sample extends Component{
state = {data : []};
componentWillMount(){
this.setState({data : inputObject});
}
render(){
return(
<View>
//you can render the data here
</View>
);
}
}
import { useEffect, useState } from 'react';
const Sample = () => {
const [state, setState] = useState([]);
useEffect(() => {
setState(inputObject);
}, [])
return(
<View>
//you can render the data here
</View>
);
}
Reference: https://facebook.github.io/react/docs/react-component.html#componentwillmount
If you want to handle back button page navigation then you need to listen to the
navigation event once when the component has mounted, use the code below for the same.
componentDidMount = () => {
this.focusListener = this.props.navigation.addListener('focus',
() => {
console.log('focus is called');
//your logic here.
}
);
}
This can be easily accomplished using 'withNavigationFocus' , found in the react native documentation here
import React, { Component } from 'react';
import { View } from 'react-native';
import { withNavigationFocus } from 'react-navigation';
class TabScreen extends Component {
componentDidUpdate(prevProps) {
if (prevProps.isFocused !== this.props.isFocused) {
// Use the `this.props.isFocused` boolean
// Call any action
}
}
render() {
return <View />;
}
}
// withNavigationFocus returns a component that wraps TabScreen and passes
// in the navigation prop
export default withNavigationFocus(TabScreen);
You could use a hook approach:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
I literally just copied the first example of the documentation, but it's a very good one.
If you want continue reading: https://reactjs.org/docs/hooks-effect.html
I used "onLayout" method inside the view.
read the doc
onLayout: Invoked on mount and on layout changes.
export default function Login({ navigation }) {
const executeOnLoad = () => {
console.log("view has loaded!");
};
return (
<View style={styles.container} onLayout={executeOnLoad}>
--- layout code here
</View>
);
}
Since you are dealing with the screen, I will suggest you use useFocusEffect hooks.
example:
const ExampleScreen = () => {
// your code here
useFocusEffect(useCallback(() => {
// your logic goes here
}, []))
return (
<View>
{/* render your content here */}
</View>
)
}

How to reset ReactJS file input

I have file upload input:
<input onChange={this.getFile} id="fileUpload" type="file" className="upload"/>
And I handle upload this way:
getFile(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = (theFile) => {
var data = {
blob: theFile.target.result, name: file.name,
visitorId: this.props.socketio.visitorId
};
console.log(this.props.socketio);
this.props.socketio.emit('file-upload', data);
};
reader.readAsDataURL(file);
}
If I upload same file twice, then upload event is not fired. How can I fix that? For simple js code it was enough to do the following: this.value = null; in change handler. How can I do it with ReactJS?
I think you can just clear the input value like this :
e.target.value = null;
File input cannot be controlled, there is no React specific way to do that.
Edit For old browsers (<IE11), you can use one of the following techniques.
See http://jsbin.com/zurudemuma/1/edit?js,output (tested on IE10 & 9)
What worked for me was setting a key attribute to the file input, then when I needed to reset it I update the key attribute value:
functionThatResetsTheFileInput() {
let randomString = Math.random().toString(36);
this.setState({
theInputKey: randomString
});
}
render() {
return(
<div>
<input type="file"
key={this.state.theInputKey || '' } />
<button onClick={this.functionThatResetsTheFileInput()} />
</div>
)
}
That forces React to render the input again from scratch.
This work for me - ref={ref => this.fileInput = ref}
<input id="file_input_file" type="file" onChange={(e) => this._handleFileChange(e)} ref={ref=> this.fileInput = ref} />
then in my case once the file was uploaded to the server , I clear it by using the statement below
this.fileInput.value = "";
I do it by updating key inside my file input.
This will force a re-render and previously selected file will go away.
<input type="file" key={this.state.inputKey} />
Changing the state inputKey will re-render the component.
One way to change the inputKey will be to always set it to Date.now() on click of a button which is supposed to clear the field.
With every click onClick you can reset the input, so that even with the same file onChange will be triggered.
<input onChange={this.onChange} onClick={e => (e.target.value = null)} type="file" />
import React, { useRef } from "react";
export default function App() {
const ref = useRef();
const reset = () => {
ref.current.value = "";
};
return (
<>
<input type="file" ref={ref} />
<button onClick={reset}>reset</button>
</>
);
}
The following worked for me using React Hooks. This is done using what is known as a "controlled input". That means, the inputs are controlled by state, or their source of truth is state.
TL;DR Resetting the file input was a two-step process using both the useState() and useRef() hooks.
NOTE: I also included how I reset a text input in case anyone else was curious.
function CreatePost({ user }) {
const [content, setContent] = React.useState("");
const [image, setImage] = React.useState(null); //See Supporting Documentation #1
const imageInputRef = React.useRef(); //See Supporting Documentation #2
function handleSubmit(event) {
event.preventDefault(); //Stop the pesky default reload function
setContent(""); //Resets the value of the first input - See #1
//////START of File Input Reset
imageInputRef.current.value = "";//Resets the file name of the file input - See #2
setImage(null); //Resets the value of the file input - See #1
//////END of File Input Reset
}
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Add Post Content"
onChange={event => setContent(event.target.value)}
value={content} //Make this input's value, controlled by state
/>
<input
type="file"
onChange={event => setImage(event.target.files[0])} //See Supporting Doc #3
ref={imageInputRef} //Apply the ref to the input, now it's controlled - See #2
/>
<button type="submit">Submit Form</button>
</form>
</div>
)
};
Supporting Documentation:
useState Hook
Returns a stateful value, and a function to update it.
useRef Hook
If you pass a ref object to React, React will set its current property to the corresponding DOM node whenever that node changes.
Using files from web apps
If the user selects just one file, it is then only necessary to consider the first file of the list.
You can also include this in your input element if you know you are not going to be using the built-in file input value at all.
<input value={""} ... />
This way the value is always reset to the empty string on render and you don't have to include it awkwardly in an onChange function.
I know file input is always uncontrolled however the following code still works in my own porject, I can reset the input with no problems at all.
constructor(props) {
super(props);
this.state = {
selectedFile: undefined,
selectedFileName: undefined,
imageSrc: undefined,
value: ''
};
this.handleChange = this.handleChange.bind(this);
this.removeImage = this.removeImage.bind(this);
}
handleChange(event) {
if (event.target.files[0]) {
this.setState({
selectedFile: event.target.files[0],
selectedFileName: event.target.files[0].name,
imageSrc: window.URL.createObjectURL(event.target.files[0]),
value: event.target.value,
});
}
}
// Call this function to reset input
removeImage() {
this.setState({
selectedFile: undefined,
selectedFileName: undefined,
imageSrc: undefined,
value: ''
})
}
render() {
return (
<input type="file" value={this.state.value} onChange={this.handleChange} />
);
}
We can reset file input by using key = {this.state.fileInputKey} and initialsing fileInputKey to Date.now() in constructor state.
On file upload success , we need to again assign fileInputKey: Date.now(), so it will have different value than previous and it create new file input component on next render()
We can also do this manually by clicking button to clear/reset file Input
Below is the working code :
import React from "react";
import { Button } from "reactstrap";
class FileUpload extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null,
fileInputKey: Date.now(),
message: ""
};
this.handleClear = this.handleClear.bind(this);
this.onClickHandler = this.onClickHandler.bind(this);
this.onChangeHandler = this.onChangeHandler.bind(this);
}
onChangeHandler = event => {
this.setState({
selectedFile: event.target.files
});
};
onClickHandler = () => {
if (this.state.selectedFile === null) {
this.setState({
message: "Please select File"
});
return;
}
//axios POST req code to send file to server
{
/**
const data = new FormData()
data = this.state.selectedFile[0]
axios.post("http://localhost:8080/api/uploadFile/", data)
.then(res => {
if (res.status == 200) {
// upload success
}
})
.catch(err => {
//message upload failed
})
*/
}
//after upload to server processed
this.setState({
selectedFile: null,
fileInputKey: Date.now(),
message: "File Uploaded"
});
};
handleClear() {
this.setState({
selectedFile: null,
fileInputKey: Date.now(),
message: ""
});
}
render() {
return (
<div>
<input
type="file"
key={this.state.fileInputKey}
class="form-control"
onChange={this.onChangeHandler}
/>
<button
type="button"
class="btn btn-success btn-block"
onClick={this.onClickHandler}
>
Upload
</button>
<Button
type="button"
value="Clear"
data-test="clear"
onClick={this.handleClear}
>
{" "}
Clear{" "}
</Button>
<br />
<label>{this.state.message}</label>
</div>
);
}
}
export default FileUpload;
Here is my solution using redux form
class FileInput extends React.Component {
constructor() {
super();
this.deleteImage = this.deleteImage.bind(this);
}
deleteImage() {
// Just setting input ref value to null did not work well with redux form
// At the same time just calling on change with nothing didn't do the trick
// just using onChange does the change in redux form but if you try selecting
// the same image again it doesn't show in the preview cause the onChange of the
// input is not called since for the input the value is not changing
// but for redux form would be.
this.fileInput.value = null;
this.props.input.onChange();
}
render() {
const { input: { onChange, value }, accept, disabled, error } = this.props;
const { edited } = this.state;
return (
<div className="file-input-expanded">
{/* ref and on change are key properties here */}
<input
className="hidden"
type="file"
onChange={e => onChange(e.target.files[0])}
multiple={false}
accept={accept}
capture
ref={(input) => { this.fileInput = input; }}
disabled={disabled}
/>
{!value ?
{/* Add button */}
<Button
className="btn-link action"
type="button"
text="Add Image"
onPress={() => this.fileInput.click()}
disabled={disabled}
/>
:
<div className="file-input-container">
<div className="flex-row">
{/* Image preview */}
<img src={window.URL.createObjectURL(value)} alt="outbound MMS" />
<div className="flex-col mg-l-20">
{/* This button does de replacing */}
<Button
type="button"
className="btn-link mg-b-10"
text="Change Image"
onPress={() => this.fileInput.click()}
disabled={disabled}
/>
{/* This button is the one that does de deleting */}
<Button
type="button"
className="btn-link delete"
text="Delete Image"
onPress={this.deleteImage}
disabled={disabled}
/>
</div>
</div>
{error &&
<div className="error-message"> {error}</div>
}
</div>
}
</div>
);
}
}
FileInput.propTypes = {
input: object.isRequired,
accept: string,
disabled: bool,
error: string
};
FileInput.defaultProps = {
accept: '*',
};
export default FileInput;
In my case I had a functional component and after selecting a file it suppose to set the file name in the state so using any solution above was failing except the ref one which i fixed like this.
const fileUpload = props => {
const inputEl = useRef(null)
const onUpload = useCallback(e => {
uploadFile(fileDetails)
.then(res => {
inputEl.current.value = ''
})
.catch(err => {
inputEl.current.value = ''
})
})
return (
<input type='file' ref={inputEl} onChange={handleChange} />
<Button onClick={onUpload}>Upload</Button>
)
}
I recently got stumbled into this issue to reset the File type input field. I think it is still a milestone for most developers. So I thought I should share my solution.
Since we are listening to the onChange event to update the image file into some of our states, we will have our component rerendered once we set the state. In such case, we can specify the value of the input file as empty like value='' which will cause the input field to reset its value after each change of its value.
<input
type="file"
value=''
onChange={onChangeFnc}
/>