1

I am trying implement a function that takes url and navigates to the provided URL, from typescript function I am trying create a link object dynamically and simulate click event on the dynamic link? I have following code to create the link element not sure hot simulate the click

const openExternalLink = (linkAddress) => {
    const linkElement = React.createElement('a', {href: linkAddress},linkAddress);

    linkElement.click(); <-- ERROR
};

The above code not compiling following is the error message:

Property 'click' does not exist on type 'DetailedReactHTMLElement<{ href: string; }, HTMLElement>'.ts(2339)

Any idea how to simulate the click on a dynamically created UI element?

1 Answer 1

0

please refer below code sample

let elem = React.createElement(
    this.props.tag,
    { 
        style: this.props.style,
        id: this.props.id
        onClick: () => {console.log('clicked')}
    },
    [this.props.text]
)

You could also pass a predefined function like below

let elem = React.createElement(
    this.props.tag,
    { 
        style: this.props.style,
        id: this.props.id
        onClick: this.handleClick.bind(this)
    },
    [this.props.text]
)

Credit :https://stackoverflow.com/a/55370859/13988407

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

1 Comment

Thank you for sharing the code, the problem i am having is to simulate the "click" event. This will create element and binds the click event, how to simulate the click event after creating the element?

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.