user10211187
user10211187

Reputation:

How to use onClick in react.js?

How to use onClick event or really any other event like this?

import mycomponent from './path'    

class App extends React.Component{

    render()
    {
      <mycomponent onClick={console.log("Click"}/>
    }
}

How to give mycomponent onClick event?

import React from 'react'
const mycomponent = () =>{<p>Click Me</p>}

export default mycomponent

Upvotes: 2

Views: 5000

Answers (2)

Blue
Blue

Reputation: 22911

Props is the first value passed in to a function based react component:

import React from 'react'
const mycomponent = (props) =>{<p onClick={props.onClick}>Click Me</p>}

export default mycomponent

And in your App Component:

import mycomponent from './path'    

class App extends React.Component{

    render()
    {
      <mycomponent onClick={() => console.log("Click"}/>
    }
}

Upvotes: 0

jian
jian

Reputation: 1256

Here are two things worth noting:

  1. you can capture click (or other events) only on DOM elements. If you want to capture click event on your custom component, you need to delegate it to a DOM element inside the component.

  2. what you pass to onClick should be a function. Here you are passing the result of calling that function to onClick (console.log('Click') is a function call, not a function).

Here is a running example:

const MyComponent = (props) => (<p onClick={props.click}>Click Me</p>)


class App extends React.Component {
  click () {
    alert('clicked')
  }
  render() {
    return (
    <div>
      Provide a function to click event: <MyComponent click={this.click} />
      Provide an anonymous function to click event: <MyComponent click={() => alert('yes')} />

    </div>
      
      
    )
  }
}



ReactDOM.render(
  <App />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container">
</div>

Also note that this lineconst mycomponent = () =>{<p>Click Me</p>} should be

const mycomponent = () => <p>Click Me</p>

If you add curly braces, you'll need to explicitly return that value.

Upvotes: 2

Related Questions