I'm working on a markdown previewer using React (beginner) and I'm trying to display the current value of a textarea in a separate div on the page. I'm not sure how best to work with the textarea value using React.
My component hierarchy is as follows:
- App
- Editor
- Toolbar
- Textarea
- Previewer
- Toolbar
- Destination Div
- Editor
Currently I have a function in my App component that handles change to the textarea - this is passed down as props to the Editor component and further on to the Textarea component where it is called after the onChange event:
function App() {
const handleTextChange = () => {
const textarea = document.getElementById("textarea");
let text;
if (textarea === null) {
text = "";
} else {
text = textarea.value;
}
console.log(text);
return text;
};
return (
<div className="App">
<Header />
<div className="App-body">
<Editor handleTextChange={handleTextChange} />
<Preview />
</div>
</div>
);
}
export default App;
This function is working - I can see the textarea value updating in the console as I type.
Questions are as follows:
- How should I pass this value to the desination div? Does this need to involve State, so that the destination div re-renders every time the textarea value changes?
- Was declaring the handleTextChange function within my App component the right approach to begin with? Is there are better way to achieve this result?
New to React (and Stack Overflow) - any advice (or links to related questions) appreciated