Search code examples
javascriptreactjstypescriptreact-props

How to access nested props object in React TS?


I am struggling with accessing a nested prop object in React

I have a Header reusable component in which the props are className and title.

interface HeaderProps {
 className: string;
 title: ReactNode;
}

The usage of Header component is given below.

<Header className='my-header' title={<Title color='red'> title of the page </Title>} /> 

Now inside Header component I want to access color prop of Title component.

I was thinking to use props.title.props.color. But typescript throws error as

props is not assignable to "whole ReactNode Thing"

Solution

  • Change title: ReactNode to title: ReactElement

    import { ReactElement } from "react";
    import "./styles.css";
    // import * as React from 'react';
    
    interface HeaderProps {
      className: string;
      title: ReactElement;
    }
    
    const Title = ({ color }: any) => {
      return <div>TITLE</div>;
    };
    
    const Header = ({ className, title }: HeaderProps) => {
      console.log(title.props.color);
      return <div>HEADER</div>;
    };
    
    export default function App() {
      return (
        <div className="App">
          <Header
            className="my-header"
            title={<Title color="red"> title of the page </Title>}
          />
        </div>
      );
    }
    

    codesandbox - https://codesandbox.io/s/holy-cherry-n6t50?file=/src/App.tsx:0-560