1

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"
2
  • 1
    Try this ---> ` title: ReactElement;` Commented Jun 16, 2021 at 11:26
  • 1
    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. Commented Jun 16, 2021 at 11:39

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.