DEV Community

Varun D
Varun D

Posted on • Edited on

Notes on React Typescript

Creating a simple component in a new file, Component.tsx being called from App.tsx with props passed to it:

App.tsx

//standard imports
import {Component} from "./Component"

// Some state example. Array of objects - most common.
const ArrayofObj = [
  {
    id: 1
    name: "Lovelace",
    age: 32,
    cool: true
}]

export function default App(){
return (
  <>
    <Component mystuff={ArrayofObj}/>
  </>
)}
Enter fullscreen mode Exit fullscreen mode

Component.tsx

// Define type of props I get here.
// Any name that makes sense. Notice the [] at the end.
type propTypes = {
  ArrayofObj: { id: number; name: string; age: number; cool: bool }[];
// Specify it's an array using [] at the end!
};

// Accept prop with propTypes we defined above
export default function Component({ mystuff }: propTypes) {
// Create the lil pieces to put together later
  const mystuff_li = mystuff.map((item) => (
    <li key={item.id}/>{item.name} is {item.age} years old.</li>
  ));

// Return the stuffs
  return <ul>{friends_li}</ul>;
}
Enter fullscreen mode Exit fullscreen mode

Some other common ones...
Callbacks with mouse events can be found by hovering over your own function.

For example, a button with onClick={handleCancel} received from parent, the prop type in this case will be:
handleCancel: React.MouseEventHandler<HTMLButtonElement>;

Good resource for TypeScript cheatsheets.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay