Minh Nghĩa
Minh Nghĩa

Reputation: 1049

Argument of type 'Element' is not assignable to parameter of type ReactElement

I'm learning React, and playing with the clock example. The app was created with create-react-app . --template typescript.

I modified App.tsx as follow:

import React from 'react';
import Clock from './Clock';

function App() {
  return (
    <div className="App">
      <Clock />
    </div>
  );
}

export default App;

And my Clock.tsx:

import React from 'react';
import ReactDOM from 'react-dom';

class Clock extends React.Component {
    render() {
        return <div>{ new Date().toLocaleTimeString() }</div>
    }
}

export default Clock;

// My take on tick
function tick(parent: React.Component) {
    const el = <div>{new Date().toLocaleTimeString()}</div>;
    ReactDOM.render(el, parent);
}

However, it does not compile:

No overload matches this call.
  The last overload gave the following error.
    Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)>[]'.
      Type 'Element' is missing the following properties from type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)>[]': length, pop, push, concat, and 28 more.  TS2769

    14 | function tick(parent: React.Component) {
    15 |     const el = <div>{new Date().toLocaleTimeString()}</div>;
  > 16 |     ReactDOM.render(el, parent);
       |                     ^

I thought it was a problem compiling JSX.Element to ReactElement. Other answers indicate that this should works fine. I remove the function out and modify the index.tsx to

const el = <div>{new Date().toLocaleTimeString()}</div>;
ReactDOM.render(el, document.getElementById('root'));

then it does compile just fine.

How can I fix my function?

Upvotes: 1

Views: 1205

Answers (1)

Hung.LK
Hung.LK

Reputation: 84

Problem is your parent. It's type should be HTMLElement which can get by document.getElementById('root'), not JSX.Element or React.Component

If you trying example:

function tick(parent: HTMLElement | null) {
  const el = <div>{ new Date().toLocaleTimeString() }</div>;
  ReactDOM.render(el, parent);}

setInterval(() => {
  tick(document.getElementById('root'))
}, 1000);

Your needn't clock in this case.

Upvotes: 3

Related Questions