Typescript & React: Passing props between components

Diana ponce
2 min readNov 25, 2020

In React passing props to another component is very simple. As an intern at a company that uses typescript with React I am constantly learning new things about typescript. While working on a task I was assigned, I had to create a few functions that I had to pass down to another component. When I called on tat prop in my component I kept receiving a strange error I didn't understand :

so the problem here is we are not being clear on the types of props we are passing, so typescript will give us back an error. How do we fix this? well we can use typescripts interfaces to pass down props to other components!

So here we are going to make a simple todo list:

import React, { Component } from "react";import TodoList from './components/TodoList;const App: React.FC=()=>{const todos=[{id:'1',text:'finish blog'}]return(<div classname='app'><TodoList items={todos}/></div>);};export default App

so in this code snippet we are passing down our array of todos to the TodoList component which is this (our regular react component):

import react from 'react;const TodoList: React.FC=props=>{return(<ul>{props.todos.map(todo=>(<li key={todo.id>{todo.text}</li>))}</ul>);};export default TodoList

So here if we were to write it out like this typescript would give us back an error, which would look like this

since were are not telling it what type of props these are so instead we would have to write it out like this, with interfaces:

import react from 'react;interface TodosProps{items:{id:string, text:string}[];//<=== }const TodoList: React.FC<TodoListProps>=props=>{return(<ul>{props.todos.map(todo=>(<li key={todo.id>{todo.text}</li>))}</ul>);};export default TodoList

we are telling the types these props are and what props this component accepts and now the component will work and render normally. Lets say we want to pass down a function

we would write it out like this in the typescript interface

interface Props{exampleFunction:(argument1:string,argument2:string)=>void}

We also tell typescript what types the arguments are for the functions.

Typescript interfaces are simple and now if we change a name of a property we passed down, it would be easy to notice since typescript would give us back an error.

--

--