#Proper way to manage state between two sibling client components

9 messages · Page 1 of 1 (latest)

silver acorn
#

Hi everyone,
I'm new to NextJS and have been having a bit of trouble regarding state management between sibling client components. I am essentially trying to conditionally render a component in my layout, however, I wish to be able to control it using my NavBar. However, as the Layout component is always a server one, I haven't been able to figure out how to transfer and update state between the two.

Here is my code:

// layout .tsx
import React from 'react'
import Topnav from '../components/Topnav'
import NewPostForm from '../components/NewPostForm'

export default function Layout({ children }: {children: React.ReactNode}) {
  return (
    <>
    <Topnav/>
    <NewPostForm isOpen={false}/>
    <main>{children}</main>
    </>
  )
}
// topnav.tsx
import Link from 'next/link'
import React from 'react'

function Topnav() {
  return (
    <nav className=''>
        <ul className='flex flex-row gap-4 text-lg font-bold p-2 border-white border-b-2'>
            <Link href={"/"}>Home</Link>
            <Link href={"/posts"}>Posts</Link>
            <li className='ml-auto'>Login</li>
            <li>New post</li>
        </ul>
    </nav>
  )
}

export default Topnav
// newpostform.tsx
import React from 'react'
interface NewPostFormProps {
    isOpen: boolean;
}

function NewPostForm(props: NewPostFormProps) {
    if (!props.isOpen) {
        return;
    }
  return (
    <form action="">
        <input type="text" placeholder='Title'/>
        <textarea name="" id="" placeholder='Content'></textarea>
    </form>
  )
}

export default NewPostForm
night reefBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

dim abyss
#

you can however, put client component in a server component that reads a client top-level context that shares the state between all of the client component that reads the context

#
export default function Layout({ children }: {children: React.ReactNode}) {
  return (
    <NavContext>
      <Topnav/>
      <NewPostForm/>
      <main>{children}</main>
    <NavContext/>
  )
}

silver acorn
#

Thank you so much @dim abyss, that worked!

silver acorn
# dim abyss which one?

I just wrapped the components that I wanted to have the ability to control the state in a context provider

#

And it worked