brff19
brff19

Reputation: 834

Typescript not allowing me to pass props to child component

I have two components. One is the App.tsx file and inside of it, I do an API call to get some data. I take that data and try to pass it down, but I get an error Type 'Element' has no properties in common with type 'Props'. TS2559 Props is the name of my interface that I have made for the App component. The other component is just the child component that wants to receive the props.

import './App.css';
import * as React from "react";
import {useState, useEffect} from "react";
import UsersList from "./components/UsersList";
import Form from "./components/Form"

interface Props {
  userList?: any
}

const App = (): Props => {
  const [users, setUsers] = useState([])
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then(res => res.json())
      .then(usersList => {
        setUsers(usersList)
      })
      .catch(err => {
        throw new Error(err);
      })
  }, [])
  return (
    <div className="App">
      <Form />
      <UsersList userList={users}></UsersList>
    </div>
  );
}

export default App;

Upvotes: 0

Views: 860

Answers (2)

JAM
JAM

Reputation: 6205

It seems that you have misplaced your Props type. As the example stands, you are saying that the App function should return Props.

You can either define it like this:

const App = (props: Props) => {

Or you can use the types provided by React:

const App: React.FC<Props> = (props) => {

Upvotes: 1

Gabriel Lima
Gabriel Lima

Reputation: 499

If you set the type after the () ((): Props), you're defining the return type. If you want to set the type of a parameter, you need to define it inside the () ((props: Props)).

Try this:

import './App.css';
import * as React from "react";
import {useState, useEffect} from "react";
import UsersList from "./components/UsersList";
import Form from "./components/Form"

interface Props {
  userList?: any
}

const App = ({userList}: Props) => {
  const [users, setUsers] = useState([])
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then(res => res.json())
      .then(usersList => {
        setUsers(usersList)
      })
      .catch(err => {
        throw new Error(err);
      })
  }, [])
  return (
    <div className="App">
      <Form />
      <UsersList userList={users}></UsersList>
    </div>
  );
}

export default App;

Upvotes: 1

Related Questions