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} />
</>
);
};
>Solution :
You can add a state inside your Textarea component and set it to its initial value, also initialize the count corresponding:
const [textCount, settextCount] = useState(props.value.length);
const [textValue, setTextValue] = useState(props.value);
Then use the textvalue inside the textarea:
<textarea
type="text"
value={textValue}
onChange={(e) => {
recalculate(e);
props.onChange(e);
setTextValue(e.target.value)
}}
/>
if that is what your looking for here’s a working sandbox
Edit: add the improved sandbox from comments
improved version from @Leland