1

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!

2
  • can you provide the error? what does console.log(state) produce? Commented Oct 11, 2021 at 13:59
  • console.log(state) shows name and age well as object. but console.log(state.name) shows "Error: Objects are not valid as a React child (found: object with keys {name, age}). If you meant to render a collection of children, use an array instead." Commented Oct 11, 2021 at 14:04

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Now I got this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.