The code sets the textCount
to match the input onChange
, but I need textCount
to also be set to the value that comes from inside of App()
from name
.
import React, { useState } from "react";
function Textarea(props) {
const [textCount, settextCount] = useState(0);
const recalculate = (e) => {
settextCount(e.target.value.length);
};
return (
<>
<textarea
type="text"
onChange={(e) => {
recalculate(e);
props.onChange(e);
}}
/>
<p>{textCount}/5</p>
</>
);
}
export default Textarea;
const App = (props) => {
const {name} = props.stateData;
const change = async (e) => {
props.changevalue(e);
};
return (
<>
<Textarea value={name} onChange={change} />
</>
);
};
3
Answers
The value attribute on form elements will override the value in the DOM. If you want to specify the initial value, but leave subsequent updates uncontrolled, you can specify a defaultValue attribute instead of value.
You can add a state inside your Textarea component and set it to its initial value, also initialize the count corresponding:
Then use the textvalue inside the textarea:
if that is what your looking for here’s a working sandboxEdit: add the improved sandbox from comments
improved version from @Leland
You don’t need to have state for
textCount
since theTextarea
component is going to be re-rendered any time it receives a new value, therefore we can calculate thelength
of the value while rendering.Also, the
<p>
tag has to be outside the<textarea>
element, and therecalculate()
function doesn’t seem to be necessary in this case since we can get thelength
just by reading thelength
property from the value.