Answer the question
In order to leave comments, you need to log in
How to raise the state to the parent component?
I have a presentational component that is nested within a parent component. Inside the presentational component, a local state is used. This is the wrong approach, so I would like to raise the local state to the container component and then work with it through the presentational component's callbacks.
Please help me to do this. The problem is that a container component is neither an object nor a function. Therefore, I cannot use setState hooks in it.
Page1.jsx:
import React, { useState } from 'react';
function Page1(props) {
let textareaRef = React.createRef();
const [state, setState] = useState({
presentText: '',
});
function textareaSet() {
props.setAppTextCreator(textareaRef.current.value);
textareaRef.current.value = '';
}
function textareaChange() {
setState({...state, presentText: textareaRef.current.value})
}
return (
<div>
<textarea
ref={ textareaRef }
onChange={ textareaChange }>
</textarea>
<button onClick={ textareaSet }>send</button>
<div>present: { state.presentText }</div>
<div>memorized: { props.text }</div>
</div>
);
}
export default Page1;
import {connect} from "react-redux";
import { setAppTextCreator } from '../../redux/appReducer';
import Page1 from './Page1';
const mapStateToProps = state => {
return {
text: state.appReducer.appText,
presentText: state.presentText
}
}
export default connect(mapStateToProps, { setAppTextCreator })(Page1);
Answer the question
In order to leave comments, you need to log in
As far as I remember, it is impossible to raise a state in react. You can set the state above your parent component and push it down using the context.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question