0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React:Bootstrap Tabタイトルを子コンポーネントから変更

Last updated at Posted at 2021-10-07

ReactでBootstrapのTabsを使っていて、keyのあるオブジェクトから作ったTabのタイトルを子コンポーネントからkeyを指定して変更した。メモを2点ほど。

ComponentParent
export default function ComponentParent(props) {
  const [tabTitles, setTabTitles] = useState(null)
  const [currentKey, setCurrentKey] = useState(null)

  useEffect(() => {
    // ここでは、例なので単純にオブジェクト直接記述
    setTabTitles({ 111: "タブ1", 222: "タブ2", 333: "タブ3" })
    setCurrentKey(111)
  }, [])

  useEffect(() => {
    // 何か選択が変わった時の処理
  },[currentKey]}
    

  const TabSample = () => {
    if (!currentKey || !tabTitles) return <div>Loading...</div>;
    return (
      <Tabs
        id="tab-sample"
        activeKey={ currentKey }
        onSelect={(k) => setCurrentKey(k)}
      >
                {/* メモ1: オブジェクトをmapで展開するにはこう書けばよいみたい。 */}
        { Object.keys(tabTitles).map(key => <Tab eventKey={ key } title={ tabTitles[key]} key={ key }></Tab> }
      </Tabs>
    )
  }

  const changeTabTitle = (key, title) => {
    /* メモ2: tabTitles[key] = title してセットする方法だと更新されない。展開すること。 */
    setTabTitles({...tabTitles, [key]: title}) 
  }

  return (
    <TabSample />
    <ComponentChild 
       changeTabTitle={ (key, title) => changeTabTitle(key, title) } 
    />
  )
}
ComponentChild
export default function ComponentChild(props) {

 const clickChangeTabTitle1 = () => {
   props.changeTabTitle(111, "タブA")
 }

 return (
   <button onClick={ clickChangeTabTitle1 } >タブ1のタイトル変更</button>
 )
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?