Search code examples
statereact-typescript

React Typescript pass state


I am new to React TypeScript. I have a problem with the passing state. When I tried to pass the state to a child component and conosle.log(state), I can see the correct object. But, when I tried to do console.log(state.name), I have an error. How can I solve this problem?

App.tsx

export interface Information {
  name: string;
  age: string;
}

const App: FC = () => {
  const [state, setState] = useState<Information | null>({
    name: "young",
    age: "10",
  });

  return (
    <div className="App">
      <div className="header">
        <div className="inputContainer">
          <input type="text" placeholder="Task.." name="task" />
          <input type="number" placeholder="Deadline" name="deadline" />
        </div>
        <button>Add Task</button>
        <div>
          <MyForm state={state} />
        </div>
      </div>
    </div>
  );
};

Child component

type Props = {
  state: ReactNode;
};

const MyForm: FC<Props> = ({ state }: Props) => {
  console.log(state.name);  // Error
  return <div>Hello, {state}</div>;
};

export default MyForm;

Thank you!


Solution

  • The error because you're trying to read the state object inside JSX

      return <div>Hello, {state}</div>
    

    Read it like you would with objects instead:

      return <div>Hello, {state.name}</div>
    

    Also in your MyForm Component Props, use your Information interface as a type definition instead of ReactNode

    export interface Information {
      name: string
      age: string
    }
    
    type Props = {
      state: Information
    }
    

    Edit holy-sunset-30f9j