I have this NextJS(v15) component redered with SSR and want the Item
to be available for search engines. And I have a delete button that should delete this component from DOM. I can delete the parent in DeleteMeButton with getElementById(parentId) or by passing the parent ref to the DeleteMeButton. But what is the best React way to do this using SSR + use client
? Thanks.
export const Item = () => {
return (
<div>
<DeleteMeButton />
Content here
</div>
);
};
Delete.tsx
("use client");
export const DeleteMeButton = () => {
const handleDelete = () => {
//delete the parent component here
};
return <button onClick={handleDelete}>Delete me</button>;
};
Generally speaking it's not a good idea to manipulate the DOM managed by React yourself. It defeats the purpose entirely of using React.
There seems to be a misinterpretation about how client components work. Client components are still prerendered on the server, the only thing that does not execute are hooks that depend on effects (such as useState
).
This means that you can safely use 'use client'
in your Item.tsx
component file while still keeping its content available to search engines if its initial or default state contains this information.
Let's visit the solution you could implement:
Item.tsx
:
'use client';
import React, { useState } from 'react';
export const Item = () => {
const [show, setShow] = useState(true);
const handleDelete = () => setShow(false);
if (!show) return null;
return (
<div>
<DeleteMeButton onClick={handleDelete} />
Content here
</div>
);
}
Delete.tsx
:
interface Props {
onClick: () => void;
}
export const DeleteMeButton = ({ onClick }: Props) => {
return <button onClick={onClick}>Delete me</button>;
};
This will still prerender the div with Content here
to be available in search engines because show
is initialized to true
.