I have a school project were I need to use NextJS, in certain point I needed to use ContextAPI to manage some things as inputs, auths and decorative elements with buttons but every single use I cannot make it work, frustrated I made an example with basic elements following a tutorial but it didn’t work, if you have suggestions, recommendations or solutions please make me know… i’m still a little frog in this.
Here’s the example with basic elements:
Panel:
'use client';
import React, { useState } from 'react';
import './panel.css';
import Cajauno from './components/cajas';
import Cajados from './components/cajas2';
import { CambiarPanelCX } from './contexts/cambiarpanel';
function Panel() {
const [showCaja, setShowCaja] = useState(false);
return (
<>
<div class="displaycajas">
<CambiarPanelCX.Provider value={{ setShowCaja }}>
{showCaja ? <Cajados /> : <Cajauno />}
</CambiarPanelCX.Provider>
</div>
</>
);
}
export default Panel;
Boxes:
import './cajas.css';
function Cajados() {
return (
<>
<div class="cj2">
Hola2
</div>
</>
);
}
export default Cajados;
import './cajas.css';
function Cajauno() {
return (
<>
<div class="cj1">
Hola1
</div>
</>
);
}
export default Cajauno;
Panel w/button:
'use client';
import React, { useContext } from 'react';
import './panel.css';
import { CambiarPanelCX } from './contexts/cambiarpanel';
function Panelbtn() {
const { setShowCaja } = useContext(CambiarPanelCX);
return (
<>
<div class="displaycajabtn">
<button
onClick={setShowCaja}
>
Click me
</button>
</div>
</>
);
}
export default Panelbtn;
Context:
import { createContext } from 'react';
export const CambiarPanelCX = createContext({});
Main page:
import Head from 'next/head';
import './deco.css';
//Components
import Panel from '../../panel';
import Panelbtn from '@/src/panelbtn';
export default function PrincipalP() {
return (
<>
<Head>
<title>Nose</title>
</Head>
<Panel />
<Panelbtn />
</>
);
}