'How to create a link element dynamically and simulate click event react
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?
Solution 1:[1]
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]
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ajay Gupta |