#Render state as props

2 messages · Page 1 of 1 (latest)

visual bramble
#

Okay this might be stupid! but please enlighten me!

I hade two components:
`const Component1= ()={
const [showCommentBox, setShotCommentBox]

return {
content
}

const Component2= ()={

return {
<MainWrapper>
content
</MainWrapper>
}
`
In Component1, the state is being used in the content(in the return). Now I want to use the state also in Component2.

The problem is: I want to render the state together with the MainWrapper element and not <Component1 showCommentBox={showCommentBox}.

My question is: How do I reuse the state from Component1 in Component2 and render it together with <MainWrapper>.

Why? Mainwrapper contains a lot of other content and I want the state there to use for styling. If state is true the MainWrapper content will use grid in certain size if state is false Mainwrapper content will be in smaller grid.

dim gale
#

You can wrap all the components in a context provider declare your state in the root of your application and then you can use or change the state anywhere.


import React from 'react';

export const MyContext = React.createContext();
export function App() {
const [showCommentBox, setShotCommentBox] = useState()  
return (
    <MyContext.Provider value={{ showCommentBox, setShotCommentBox }}>
      <Component1/>
      <Component2/>
    </MyContext.Provider>
  )
}

then in your components :

import { MyContext } from "./App"
const Component1 = () => {
const { showCommentBox, setShotCommentBox } = React.useContext(MyContext)

return  content
   
 }