I have been trying to implement a context API solution since I want to use children states (data) in my app.js without lifting up the states. Anyways I have tried to implement it a context API solution by doing the following :
I created a folder names context and then created
Context.js. This is the code:import { createContext,useState } from "react"; export const Mycontext = createContext() const Context = ({children}) =>{ const [post, setPost] = useState([]) return( <Mycontext.Provider value={[post,setPost]}> {children} </Mycontext.Provider> ) } export default ContextI wrapped the
index.jsfile with the provider wrapper as follows:import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import Context from './context/Context'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Context> <App /> </Context> );My main goal for now is to use useState hook data or states so I can use them in higher up components, in this case I want my
post.jsfile to change usestate data in context so i can then use that data to post something inApp.jsusing a container component that takes value as a props
I will post the both post.js and container.js and app.js below
import React,{useContext,useState,useEffect,useRef} from 'react'
import '../HomeMainStyling/HomeStyling.css'
import Tweets from './Tweets'
import Context from '../../context/Context'
function Tweet() {
const tw = useRef('')
const {post,setPost} = useContext(Context);
useEffect(() => {
if (post.length) console.log(post);
}, [post]);
function PostNow(event){
event.preventDefault();
setPost((oldpost) => [tw.current.value,...oldpost]);
}
return (
<div className="tweetcontainer">
<textarea ref={tw} className="tweetinfo"></textarea>
<button className="postIt" onClick={PostNow}>tweet</button>
</div>
)
}
export default Tweet
//
the container is the following:
import React from 'react'
import '../HomeMainStyling/HomeStyling.css'
function Tweets({value}) {
return (
<h2>{value}</h2>
)
}
export default Tweets
App.js:
import Tweet from './Center/HomeMain/Tweet';
import Tweets from './Center/HomeMain/Tweets';
import { useContext,useState } from 'react';
import Context from './context/Context';
function App() {
const {post,setPost} = useContext(Context);
return (
<div className="App">
<Tweet/>
<Tweets value={post}/>
</div>
);
}
export default App;
The app should in principle post 1 h1 element for every click in Tweet components
[post,setPost]and then detructuring it like an object.{post,setPost}, did you meanconst [post, setPost] = useContext(Context);Alternatively set value as an object ->value={{post,setPost}}