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]
)
React events are written in camelCase syntax: onClick instead of onclick . React event handlers are written inside curly braces: onClick={shoot} instead of onClick="shoot()" .
Using React without JSX is especially convenient when you don't want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React. createElement(component, props, ...children) . So, anything you can do with JSX can also be done with just plain JavaScript.
Working code: import React from "react"; import ReactDOM from "react-dom"; import uuid from "uuid"; import "./styles. css"; class App extends React. Component { state = { items: [{ id: uuid(), text: "" }] }; addListItem = () => { const newItem = { id: uuid(), text: "" }; this.
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]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With