Home > Back-end >  How to pass in props in react directly as constants?
How to pass in props in react directly as constants?

Time:10-08

How to write the type inside props which are being passed directly as constants e.g. const ComponentName = ({tasks: TaskType[]}) => {return (<>{tasks[0]}</>)}?

My TaskType is stored as an interface in another file. I don't want to use Props and write the name of each prop directly but typescript is giving me lots of error.

the files can be found here https://codesandbox.io/s/great-pare-m8ei2?file=/src/App.tsx

CodePudding user response:

The correct way to type functional components is using the React.FC type from react. SOmething like this:

const AddTaskForm: React.FC<{tasks: TaskType[], setTasks: React.Dispatch<React.SetStateAction<TaskType[]>>}> = ( {tasks, setTasks} ) => {
...
}

export default AddTaskForm;

CodePudding user response:

Here is a solution where you keep the types close to the arguments

(_: {
  tasks: TaskType[],
  setTasks: React.Dispatch<React.SetStateAction<TaskType[]>>
})

It should be noted that this syntax is global to typescript function arguments, and has nothing in particular to do with ReactJS

  • Related