12

Following is the code that I'm using to create an HTML tag. I want to add a click event on this. How can I add this?

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

1 Answer 1

21

If you are creating an HTML tag, you simply need to pass on the onClick as a function to the element as props. With React.createElement you can write it like

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]
)
Sign up to request clarification or add additional context in comments.

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.