how to pass ‘setSomeState’ to children

I’m trying to build an app with a chat block that does not refresh on page change. The child pages contain prompts to save the user from typing common responses. All my pages live within a /board directory that has a top level page called ‘BoardContainer,tsx’:

'use client'
import React, { ReactElement, ReactNode } from 'react';
import { useState } from 'react';
import { usePathname } from 'next/navigation';
import ChatBlock from '../components/ChatBlock/ChatBlock';
import AboutPage from '../dashboard/about/background/page';

interface BoardContainerProps {
  children: ReactNode;
}

const BoardContainer: React.FC<BoardContainerProps> = ({ children }) => {
  const [selectedPrompt, setSelectedPrompt] = useState('');
  const pathname = usePathname();

  const sendPrompt = (prompt: string) => {
    setSelectedPrompt(prompt);
  }

  const childrenWithProps = React.Children.map(children, child => {
    console.dir(child);
    if (React.isValidElement(child)) {
      return React.cloneElement(child as ReactElement<any>, { sendPrompt });
    }
    console.dir(child);
    return child;
  });

  console.dir(pathname);

  return (
    <>
      <>
        { pathname === '/board/about' ?  <AboutPage sendPrompt={sendPrompt} /> : <PageContent sendPrompt={sendPrompt} /> }
        {/* This works but not suitable for more than 2 child pages */}

        {/* childrenWithProps */}
        {/* this doesn't work either */}

        {/* children */}
      <>

      <>
        <ChatBlock
          prompt={selectedPrompt}
        />
      </>
    </>
  )
}

export default BoardContainer;

I figured a work-around using usePathname and essentially hard coding the child value and passing the sendPrompt function, but this is cumbersome.
I tried using React.cloneElement, but I’m either using this incorrectly or misunderstanding something. How can I pass the sendPrompt function via { children }?

You’ll use a callback function…
<ChatBlock prompt={selectedPrompt} setSelectedPrompt={setSelectedPrompt} />
Then for the prop in chat block component itself…
setSelectedPrompt: React.Dispatch<React.SetStateAction<string>>;
Then for the place you’re using it in your chat block code…
onClick={() => setSelectedPrompt('prompt1')}

New contributor

Ayomide Emmanuel Akintan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

One way to solve this is to use useContext link

Create a provider in BoardContainer

export const SendPromptContext = createContext<Function>(() => {});

const [selectedPrompt, setSelectedPrompt] = useState('initial prompt');
const sendPrompt = (prompt: string) => {
  setSelectedPrompt(prompt);
};

<SendPromptContext.Provider value={sendPrompt}>
  <div>{selectedPrompt}</div>
  {children}
</SendPromptContext.Provider>

Subscribe to the context and get sendPrompt in your client side components like this:

const sendPrompt = useContext(SendPromptContext);

Working sample: https://stackblitz.com/edit/stackblitz-starters-yqbyrm?file=app%2Flayout.tsx

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật