javascript-events,reactjs , How do I bind react events from a mixin?

How do I bind react events from a mixin?


Tag: javascript-events,reactjs

I want to write a simple mixin for a tooltip. I already know how to bind my mixin to DOM events:

componentDidMount: function() {
    var el = this.getDOMNode();
    el.addEventListener('mouseenter', this.mouseenter, false);
    el.addEventListener('mouseleave', this.mouseleave, false);

...but I'd like to bind to the React events instead, to take advantage of its consistent event system. How do I do it?


I think you probably want to do this in the render method of the mixing component, by passing in the mixin's mouseenter and mouseleave handlers as props. I think one option might look like this:

var MouseMixin = {

    getMouseProps: function() {
        return {
            onMouseEnter: this.mouseenter,
            onMouseLeave: this.mouseleave

    mouseenter: function() {
        console.warn('mouseenter', arguments)

    mouseleave: function() {
        console.warn('mouseleave', arguments)

Then, in addition to mixing this in, you'd need to apply the behavior. In JSX in React 0.12, you can use the ... spread operator to help with this:

var Example = React.createClass({

    mixins: [MouseMixin],

    render: function() {
        return (
          <div { ...this.getMouseProps() }>
              Hello world


See a working fiddle here.


How do I load SVGs directly in my React component using webpack?

I would like to render a material design icon directly in my NextButton component using webpack. Here's the relevant part of my code: var NextIcon = require('material-design-icons/navigation/svg/production/ic_chevron_right_18px.svg'); var NextButton = React.createClass({ render: function() { return ( <Link to={} className='button--next'> {this.props.label} {NextIcon} </Link> ) } }); But this isn't working as...

How to get a deleted element in a contenteditable div?

I set the root div to contenteditable, and it contains many img and video elements. So when a user edits it and presses backspace to delete one element, How can I get which one the user deleted and get the deleted element's attributes values?

html Forms inside reactJS

I used the (almost) exact syntax for creating an html form in react: var Hello = React.createClass({ render: function() { return <div> <section> <form action="http://localhost:9203/ask"> Text: <input type="text" name="text" value="Text"/> <br/> Focus: <input type="text" name="focus" value="Focus"/> <br/><br/> <input type="submit" value="Submit"/> </form> </section> </div>; } }); React.render(<Hello name="World" />, document.getElementById('container'));...

Expected corresponding JSX closing tag for input Reactjs

While creating a component in Reactjs with input fields error occurs Error: Parse Error: Line 47: Expected corresponding JSX closing tag for input at http://localhost/chat-react/src/script.js:47:20 </div> var Main = React.createClass({ render: function() { return ( <div className="card-action"> <i class="mdi-action-account-circle prefix"></i> <input id="icon_prefix" type="text" class="validate"> </div> ); } }); ...

Dynamic className in cjsx

I am trying to hide a component and update the image in a button when I click said button. I have managed to hide the component by doing the follow: {<MyAwesomeComponent /> unless @state.hide} And I change the state by doing: toggleComponent = -> @setState hide: [email protected] . . ....

ReactJs - Using Mixins with ES6

Following up on's video - 'React Components in ES 6 classes', the below works: 'use strict'; import React from 'react'; import Button from './components/form/button'; import Label from './components/form/label'; // after refactoring //import ReactMixin from './super-classes/react-mixin'; //ToDo: Reactor below let reactMixin = InnerComponent => class extends React.Component { constructor() {...

ReactJS passing a prop that the element owns to a function

I am trying to return a <li> element with an eventListener. But I want the <li> to pass a property it owns to a function onClick. This is specifically what I am talking about: return (<li onClick={this.changeTab(tab_id)} tab_id={index + 1} <a href="#">{obj.display_name}</a></li>); But if you do something like this, you...

difference between componentDidMount and getInitialState in Reactjs

I understand that getInitialState is called once in the component's lifecycle and componentDidMount is called when the component is rendered. So does that mean both will get called just once in the component's lifecycle? What's the difference?...

react-native this.setState not working

I know there's already a similar question but there's no code shared in there. Under navbarChanged() > if condition, I'm doing a this.setState. This is of type HomeTab but setState doesn't seem to be working. Any clues/pointers? class HomeTab extends React.Component { constructor() { super() this.setState({ isNavBarHidden: false }); }...

Create CRUD UI in reactjs with backend api

Ive created a CRUD app in laravel, but now i want to improve the UI with react.js. Im still very new to react, so not sure how to go about doing this. So far i have created a table component that displays all the users with react. how should i...

Javascript function called with button onclick, fails with onload

I am trying to use an external javascript function in the body tag : <!DOCTYPE html> <script type="text/javascript" src="js/Long.min.js"></script> <script type="text/javascript" src="js/ByteBufferAB.min.js"></script> <script type="text/javascript" src="js/ProtoBuf.min.js"></script> <script type="text/javascript" src="js/fs.js"></script> <script type="text/javascript" src="js/bundle.js"></script> <script type="text/javascript"...

JQuery .animate() not working with ReactJS?

I am trying to highlight a cell when the user click on it by using jQuery .animate() clickHandler: function() { var cell = React.findDOMNode(this.refs.cell); // $(cell).css("background-color", "blue"); // THIS WORK $(cell).animate({ backgroundColor: "blue" }, 1000); // THIS DOESN'T WORK }, I am also using React.addons.CSSTransitionGroup. Maybe there is a conflict...

conversion of string to JSON object in javascript with eval() [duplicate]

This question already has an answer here: Eval() = Unexpected token : error 7 answers I am converting the following JSON variable to string, and back to JSON, and getting error (in ReactJS, although it shouldn't be important) var questionGlobal = { "questionCons": [{ "string": "In", "alignment": 2 },...

Should every object in the store state be immutable?

I am learning React.js and Flux, and I understand that is better to keep the object immutable because comparing them is O(1). My situation is this: I have a store, which has a _state object, that is a map (I'm using Immutable-js). That _state has some booleans, some strings and...

ReactJS code with and without class definitions: which one is preferred?

Structurally, how different are these two code? Aren't they (almost) equivalent? In what situations one is preferred over the other? var Hello = React.createClass({ render: function() { return ( <div>Hello World</div> ); } }); React.render(<Hello />, document.body); and class SampleApplication extends React.Component { render() { return ( <div>Hello World</div> );...

Should I pass all the state in every change from store to component?

I am new on React and Flux and I am making an app that will have an input (like the name or the title), and below a list of n things. How should I handle the event listeners? I saw in the TODO example of flux ( that they use...

jQuery event.preventDefault() don't work unless debugging

I am trying to use this approach in order to convert GET parameters to POST. I also want the anchor to be properly handled even if the middle mouse button is clicked. This is how I did the the event handlers binding: $(document).ready(function () { $(".post").each(function(){ $(this).mousedown(function(evt){ switch(evt.which){ case 1:...

No call function of parent in Reactjs

I have two function in Reactjs. When function one call a function of function two. There have error same as "Uncaught TypeError: this.props.onButonShowClick is not a function" This is function one : var HiddenEdit = React.createClass({ _handleOnClick: function(e) { e.preventDefault(), this.props.onButonShowClick(true); }, render: function() { return (<span className="col-lg-2 btn-action-group"> <a...

Change the functionality of a button

Currently I have a display where I have a button START, on click of this button the timer starts and it gets replaced by 2 buttons. these 2 buttons are submit and walkaway. on the submit of each of these buttons a script is run. on the click of submit...

Better/faster way for changing React array state than cloning it?

Whenever a React class has a state object that is or contains an array, updating that state feels awkward. Usually what I do is var newArrayThing = _.clone(this.state.arrayThing); //or slice() newArrayThing[123] = 42; //update stuff this.setState({arrayThing: newArrayThing}); Is there a better or more elegant way of handling this I am...

React from NPM cannot be used on the client because 'development' is not defined. The bundle was generated from Webpack

I'm creating a React Node.js app and I'm trying to generate a Webpack bundle containing the React source code I loaded from NPM. However, it seems that the React code from NPM cannot be used directly in the client. It triggers this error: Uncaught ReferenceError: development is not defined The...

React Component with subcomponents or render HTML in parent?

I have a question regarding React patterns. When rendering a component, is it appropriate for this component to render several sub-components, or is it ok to render some HTML in the parent component. Example: If I have a box that has a heading and a body with list of elements,...

Page update when clicking a button (reactjs)

Suppose I want to render page again, after clicking a button. How can I accomplish it? In particular how would you change my program to generate random texts, when clicking the button? var colors = ['red', 'yellow', 'blue', 'green']; var Hello = React.createClass({ randomText(color) { var style = { color:...

React page layout using react-router

I have a default layout page here using react router: Header = require('./components/Header'), Footer = require('./components/Footer'), var sampleApp= React.createClass({ getDefaultProps() { return { title: 'Page One' }; }, render: function (){ return ( <div className="app"> <Header title={this.props.title} /> <RouteHandler /> <Footer /> </div> ); }, }); var routes = (...

Unable to render second react component

I am just fiddling with react to make a simple website. So here's the code <html> <head> <script src=""></script> <!-- In-browser JSX transformer, remove when pre-compiling JSX. --> <script src=""></script> <link rel="stylesheet" href=""> </head> <body> <div class="container"></div> </body> <script type="text/jsx"> var...

How to access nested object in React js 0.13.3

The below added code is working fine in React js 0.10.0. I wanna run same code in 0.13.0 version also. My main requirement is accessing nested object as default object like "". <!doctype html> <html> <head> <title>Weather Widget</title> <link rel="stylesheet" href="weather.css" /> <script src=""></script> <script src=""></script> <script...

Encapsulation with React child components

How should one access state (just state, not the React State) of child components in React? I've built a small React UI. In it, at one point, I have a Component displaying a list of selected options and a button to allow them to be edited. Clicking the button opens...

react-router go back a page how do you configure history?

Can anyone please tell me how I can go back to previous page rather than a specific route? When using this code: var BackButton = React.createClass({ mixins: [Router.Navigation], render: function() { return ( <button className="button icon-left" onClick={this.navigateBack}> Back </button> ); }, navigateBack: function(){ this.goBack(); } }); Get this error, goBack()...

reactjs Uncaught TypeError: Cannot read property 'map' of undefined

I have used getInitialState on my BrowseWidgetBox component. Although when passing the data to my MainMenu component, the data remains empty, as if the AJAX call to the api was never run in the BrowseWidgetBox. My question then, is why is this happening? Shouldn't componentDidMount call the ajax api and...

React js css transitions on class removal

I have column that should have different width depending on some flag. I use Bootstrap, so I assign col-xs-12 and col-xs-2 depending on the flag. Now I want it to change width slowly with css transition. I've read official React.js doc about transitions, but it doesn't apply to my case:...

Dynamic key in immutability update helper for array

javascript,reactjs,ecmascript-6 I have an update function that receives an index along with the event so as to alter the value for that specific item in the array. How do I get index to be evaluated instead of treated as a set key in this scenario? Is it even possible? updateValue:...

Jest - How to find rendered DOM component with id?

I am writing a simple Jest test that verifies that my component rendered. I see that React's TestUtils has functions for finding rendered components by class or by tag, but not by their ID attribute. There is a findAllInRenderedTree function, but the documentation does not explain what the callback should...

Cart not adding correct item in React.js

I'm learning React.js (and I'm a beginner at JavaScript) and having some difficulty getting my addToCart function working properly. I've managed to get all my products to display but adding to cart on any of them only adds the first item, and once that item is out of stock then...

React components as plain JS objects?

Does anybody has experience in working with React components as plain JS objects instead of annoying ES6 classes and deprecated .createClass method. Maybe you have some examples of factory functions or similar to share? Thanks!...

What WheelEvent.deltaZ refers to?

While I was working on JavaScript events, I found a troubling element on the wheel event: the deltaZ member. I understood what was deltaX as horizontal scroll (available with some devices like a touchpad) and deltaY as vertical scroll (that is what any standard wheel do) but for deltaZ, the...

What is the proper way to get the value of a React