#How to render new components in real time?
1 messages · Page 1 of 1 (latest)
Hi @odd oriole. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To create a dynamic UI where clicking on a <Pill/> component adds a new one in real-time, you'll need to use Client Components in Next.js. This is because you need interactivity with state management, which requires client-side JavaScript.
Here's how you can implement this:
- First, create a Client Component by adding the
'use client'directive at the top of your file:
'use client'
import { useState } from 'react'
export default function PillContainer() {
const [pills, setPills] = useState([{ id: 1, label: 'Pill 1' }])
const addPill = () => {
const newPill = {
id: pills.length + 1,
label: `Pill ${pills.length + 1}`
}
setPills([...pills, newPill])
}
return (
<div className="pill-container">
{pills.map((pill) => (
<Pill
key={pill.id}
label={pill.label}
onClick={addPill}
/>
))}
</div>
)
}
function Pill({ label, onClick }) {
return (
<button
className="pill"
onClick={onClick}
>
{label}
</button>
)
}
This implementation uses React's useState hook to manage the list of pills. When a pill is clicked, the addPill function is called, which adds a new pill to the state array. React will then re-render the component with the updated list of pills.
The 'use client' directive is crucial here because it tells Next.js that this component needs to be rendered on the client side where interactive features like state and event handlers are available. As mentioned in the Next.js documentation, Client Components allow you to "write interactive UI that is prerendered on the server and can use client JavaScript to run in the browser" Client Components.
For better performance, you might want to wrap your dynamic component in a Suspense boundary, especially if your app uses static rendering. This allows the static parts of your page to be rendered immediately while the dynamic parts load separately useSearchParams Behavior.
Remember that all child components of a Client Component are also considered part of the client bundle, so you don't need to add 'use client' to the Pill component separately.