1

I recently upgraded typescript and I am getting the above error in one of my components.

I have the following code in that component render method:

render() {
   const Tag = props.link ? 'a' : 'div';
   return (
      <Tag className="dummy"> text </Tag>
   );
}

When I return div or a directly in my code, it works correctly. When I return Tag it fails!

EDIT: Open issue in Github: https://www.github.com/Microsoft/TypeScript/issues/28768

4
  • 1
    You can't dynamically construct elements like that. 'a' isn't a React element, it's a string. Commented Nov 29, 2018 at 20:13
  • What about const Tag = (props) => React.createElement(props.link ? 'a' : 'div', { className: "dummy" }, props.children); However this is just a simple component that you could initialize outside the class. Commented Nov 29, 2018 at 20:23
  • What you are doing in valid JS. I just had a similar issue when updating from TS 3.1.6 to 3.2.1 so it might be an issue with the last TS update... Commented Dec 3, 2018 at 23:59
  • 1
    Related issue: github.com/Microsoft/TypeScript/issues/28768 Commented Dec 4, 2018 at 0:01

2 Answers 2

1

Your code is interesting. I tried it out in Codesandbox and it works for me with TypeScript.

I might using different TypeScript version or tsconfig. Or you use tslint. You can check the example out here. What is the difference?

I used this code, you can repleace the link to '' and it works that way too.

import * as React from "react";
import * as ReactDOM from "react-dom";

interface Props {}

enum TagTypes {
  a = 'a',
  div = 'div'
}

class Hello extends React.Component<Props, {}> {
  render() {
    let link = "#";
    const Tag: TagTypes = link ? TagTypes.a : TagTypes.div;
    return (
      <Tag className="dummy" href={link}>
        text
      </Tag>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Hello />, rootElement);

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

2 Comments

const Tag: any fixed this error!! I believe it is expecting a type for Tag. Can you please tell me what would be the type other than any? string fails
I made some experiment with the code. It works for me with enum. It is much better than any I think. I updated the answer accordingly.
0

Inside render you have declared const Tag as string.

Now inside return block, React will search for JSX syntax, here React expect Tag as element/class.

If you remove const Tag = ... you will get an error saying Tag is not defined or similar

Lastly, Datatype is mismatching in your problem statement.

Comments

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.