1
votes

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"
1
Try this ---> ` title: ReactElement;` - Sarun UK
Wow... problem solved as of now. But I found recently that this is bad practice to do so. Please add this in the answer. I'll accept it. - Subrato Patnaik

1 Answers

1
votes

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