I searched for similar questions but none fulfilled my doubt. How can I change the "this" to a react functional component in the situation: <SimpleStorage parent={this}/>
where this Component belongs to a lib (called react-simple-storage) and is written inside a functional component.
All examples I saw were refering to this.state
or this.object
or this.function
but none was about the this
alone .
const Books = () => {
...
return <Router>
<SimpleStorage parent={this}/>
<Routes/>
</Router>
When I try running this way he runs but the console throws:
No "parent" prop was provided to react-simple-storage. A parent component's context is required in order to access and update the parent component's state.
Try the following: <SimpleStorage parent={this} />
How can I set the component State of a functional component? do I have to instantiate a variable in parent component? is something that can be done?
1 Answer 1
This lib is designed to work with class components, so it would be best if you use that type of component.
However, if you look at the source code of the lib you can see that parent
uses two props: state
and setState
, so you can create a state container that will keep all the function component state:
const [state, setState] = useState(initState);
and then pass it to the :
<SimpleStorage parent={{state, setState}} />
3 Comments
setState
from useState
behaves differently to setState
from a class component so this may not work eitherExplore related questions
See similar questions with these tags.
Books
is a functional component, which uses an arrow function. Arrow functions do not have their ownthis
.