Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React router with typescript how to import intrinsic attributes

first time using Typescript, i’m rendering a component inside of a map like this:

interface chatInterface {
  sender: string;
  avatar: string;
  content: string;
  time: string;
}
<>    
  {eachUser?.chats.map((item) =>
                  item.messages.map((obj: chatInterface, index: number) => {
                    return <ChatPage key={index} message={obj} />;
                  })
                )}
</>

And the ChatPage component is this:

function ChatPage(props: { message: chatInterface }) {
  const { sender, avatar, content, time } = props.message;
  return (
      <div>
        <ul>
          <li>
            <strong>{sender}:</strong> {content} at:{time}
          </li>
        </ul>
    </div>
  );
}

And it’s working fine, but i want to create a page for the ChatPage component, but i don’t know how i should import it in the react router. This is my app.tsx component:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<Router>
        <Navbar />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/profile" element={<Profile />} />
          <Route path="/chat" element={<ChatPage />} />
        </Routes>
      </Router>

It says that

Property 'message' is missing in type '{}' but required in type '{ message: chatInterface; }'

Thanks in advance

>Solution :

It looks like the ChatPage component is missing a better type declaration. The error is saying that the message prop is required and missing. In other words, it isn’t an optional prop.

Make message an optional property and handle the destructuring fallback value in the component.

Example:

interface chatPageInterface {
  message?: chatInterface;
}

function ChatPage(props: chatPageInterface) {
  const { sender, avatar, content, time } = props.message || {};
  return (
      <div>
        <ul>
          <li>
            <strong>{sender}:</strong> {content} at:{time}
          </li>
        </ul>
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading