0

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?

asked Jul 23, 2021 at 9:02
3
  • 1
    Books is a functional component, which uses an arrow function. Arrow functions do not have their own this. Commented Jul 23, 2021 at 9:15
  • Don't confuse function components with functional programming; they are very different things. Commented Jul 23, 2021 at 9:26
  • Looks like that library's just out-of-date, there's an abandoned looking PR to support function-based components: github.com/ryanjyost/react-simple-storage/pull/30. Commented Jul 23, 2021 at 10:54

1 Answer 1

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}} />
answered Jul 23, 2021 at 9:23

3 Comments

setState from useState behaves differently to setState from a class component so this may not work either
ok! I'll try, thanks for answering quickly! if it works I'm gonna mark yours as answer
oh, I am supposed to just create a hook inside the "Books" and send it like you said?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.