Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add click event with React createElement

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]
)
like image 343
Hareesh Avatar asked Mar 27 '19 06:03

Hareesh


People also ask

How do I apply onClick event in Reactjs?

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()" .

Can you use createElement in React?

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.

How do you make a element on a button click in React?

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.


1 Answers

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]
)
like image 70
Shubham Khatri Avatar answered Oct 01 '22 10:10

Shubham Khatri