how to access methods of an instance of a React component? - reactjs

Is there a way to call the methods that a React component defines internally?
I understand generally we want to be passing values around declaratively with props/data etc. However I am using some component libraries that have internal useful methods.
eg
var field = <AutoComplete/>;
field.setValue("ready"); // doesn't work
eg this method
https://github.com/callemall/material-ui/blob/master/src/auto-complete.jsx#L244-L248
in material-ui AutoComplete component.

You can not do this with virtual dom, since virtual dom is just a description of components to be created(actual component instance will be created or updated only when rendering).
But you can access component instances inside your react component after rendering using refs:
var Test = React.createClass({
getInitialState: function(){
return {value:0};
},
setValue: function(value){
this.setState({value:value});
},
render: function() {
return <div>Value {this.state.value}</div>;
}
});
var App = React.createClass({
render: function() {
return <div>
<Test ref="test"/>
<button onClick={()=>this.refs.test.setValue(1)}>1</button>
<button onClick={()=>this.refs.test.setValue(2)}>2</button>
<button onClick={()=>this.refs.test.setValue(3)}>3</button>
</div>;
}
});
var mountNode = document.getElementById('app');
ReactDOM.render(<App name="John" />, mountNode);
jsbin with code above: http://jsbin.com/kitehujaje/1/edit?js,output

Related

React Server Side rendering: how can I know my component is mounted on the client side?

Note: I'm using the beautiful library react-rails though it should not impact the answer as far as I understand my problem.
I have a <Component /> which loads a <Map />, which implies client-side rendering as it doesn't make sense on the server side (at least the lib I'm using doesn't do that).
So instead, I want to display an image before the clientside is ready, to apply the Skeuomorphism principle.
Basically, this means I have:
var Component = React.createClass({
render: function() {
var content;
if (this.state.clientSideReady) { // How can I change my component state here?
content = <Map />
} else {
content = <PlaceholderImage />
}
return (<div>{content}</div>)
}
});
From my current understanding, componentDidMount is called on the server-side, when the template string is generated. How can I know the component actually mounted on the clientside so I can replace my image by the actual map?
My mistake. As from this answer componentDidMount isn't called on the server-side.
So I can go:
var Component = React.createClass({
getInitialState: function() {
return {
clientSideReady: false
}
},
componentDidMount: function() {
this.setState({
clientSideReady: true
});
},
render: function() {
var content;
if (this.state.clientSideReady) {
content = <Map />
} else {
content = <PlaceholderImage />
}
return (<div>{content}</div>)
}
});

How to bind event handler function dynamically in React

All:
I am pretty new to React, say I have a very simple case:
var React = require("react");
var ReactDOM = require("react-dom");
var Todo = React.createClass({
render: function() {
return (<div>Hello there
<button id="switch_func">Switch</button>
</div>);
}
});
ReactDOM.render(<Todo />, document.getElementById("div1"));
What I am trying to bind is:
There are multiple handler functions, each time when that button switch_func gets clicked, it will randomly choose another handlers and bind to itself.
But I do not know how to bind it like in AngularJS or jQuery, cos I am not sure if I can do same thing to the virtual DOM:
$("button#switch_func").on("click", function(){
$(this).off("click");
$(this).on("click", anotherHandler);
});
To bind functions you can use onClick
Simply put
<button onClick={this.handleClick}>Switch</button>
And handle the click event on the component's function:
var Todo = React.createClass({
handleClick: function(){
//put your function here!
},
//other functions in your component (e.g. render, getInitialState, etc)
});

Why is TestUtils.Simulate.click in Jest not working when used directly on React Components?

Let's say I have 2 components. A parent that contains a child.
The child component is a button like so:
var React = require('react');
var ChildButton = React.createClass({
onSubmitAnswer: function(e) {
this.props.onClick(this);
},
render: function() {
return (
<div className={this.props.visibility}>
<button onClick={this.onSubmitAnswer}>Click Me</button>
</div>
)
}
});
module.exports = ChildButton;
It lives within it's parent, which looks like this:
var React = require('react'),
ChildButton = require('./face-submit-button');
var ParentComponent = React.createClass({
onButtonSubmit: function() {
//Something happens here
},
render: function() {
return (
<div>
//Some more components
<ChildButton text="Submit" onClick={this.onButtonSubmit} />
</div>
)
}
});
module.exports = ParentComponent;
So far so good. Everything works as expected in the UI. But I've encountered some issues in the Jest tests using TestUtils.Simulate.click().
My test for the ChildButton component is straightforward and behaves as I would expect.
jest.dontMock('./child-button');
describe('ChildButton', function() {
var React = require('react/addons'),
ChildButton = require('./child-button'),
TestUtils = React.addons.TestUtils;
describe('events', function() {
var button,
onClickStub;
beforeEach(function() {
onClickStub = jest.genMockFn();
button = TestUtils.renderIntoDocument(
<ChildButton onClick={onClickStub} />
);
});
it('should call onSubmitAnswer when the button is clicked', function() {
var buttonTag = TestUtils.findRenderedDOMComponentWithTag(button, 'button');
TestUtils.Simulate.click(buttonTag);
expect(onClickStub).toBeCalled();
});
});
});
My test for the parent component started out looking the same:
jest.dontMock('./parent-component');
describe('ParentComponent', function() {
var React = require('react/addons'),
ParentComponent = require('./parent-component'),
ChildButton = require('./child-button'),
TestUtils = React.addons.TestUtils;
describe('events', function() {
var parent,
onClickStub;
beforeEach(function() {
onClickStub = jest.genMockFn();
parent = TestUtils.renderIntoDocument(
<ParentComponent onClick={onClickStub} />
);
});
it('should call onButtonSubmit when a click is triggered', function() {
var childButton = TestUtils.findRenderedComponentWithType(parent, ChildButton);
TestUtils.Simulate.click(childButton);
expect(onClickStub).toBeCalled();
});
});
});
But this test fails. The only difference I can see between these two tests is that one uses an HTML tag directly and clicks on it, while the other triggers a click on a React component. Can I not use the click event on React components directly? Is my assumption correct?
And if so, is there a way to trigger a click on React components differently in the tests? I tried using SimulateNative but that had the same effect, the onClickStub doesn't get called on click.
There is currently an open bug for this issue: Let ReactTestUtils.Simulate.click work on non-dom components. So the answer is that due to bugs, you can only use Simulate.click on an actual DOM node. So you can workaround the bug by getting the DOM node until it is fixed.

When should I use getInitialState in a React component

I have a React component that toggles a className when the component is clicked
var Foo = React.createClass({
getInitialState: function() {
return {className: ''}
},
render: function(){
var className = 'bar ' + this.state.className
return React.createElement('div', {className: className, onClick: this.onClick})
},
onClick: function() {
this.setState({className: 'baz'})
}
});
It works fine, but when I am rendering the app server side, I get the following error
Warning: getInitialState was defined on a component, a plain JavaScript class.
This is only supported for classes created using React.createClass.
Did you mean to define a state property instead?
My build step is setup like so
var Foo = require('./Foo');
var factory = React.createFactory(Foo);
module.exports = React.renderToString(factory({}));
Why is what I am doing wrong, and how should it be done?
I am not sure if this helps, but while using fluxible, this is the syntax i used with JSX as part of require component
var app = new Fluxible({
component: React.createFactory(require('./Components/startup.react.jsx'))
});

can we attach click handlers to custom child components

I was trying to add a click handler to my own child component. In react chrome extension I was able to see the click handler as well.
But the click itself didn't work - wondering what did I miss.
Sample Code:
...
render (
<MySampleComponent onClick={this.handler} />
);
...
MySampleComponent can take whichever props it wants; components don't automatically copy props to their children. If you want to be able to add an onClick handler to MySampleComponent, then you can support this in the definition of that component:
var MySampleComponent = React.createClass({
render: function() {
return <div onClick={this.props.onClick}>...</div>;
}
});
You can add the handler from the samecomponent or call it through props.
Below code looks for onClick param in props. If nothing is passed, then
it goes for default handler in the component(clickHandler).
var MySampleComponent = React.createClass({
clickHandler: function(){
// write your logic
},
render: function() {
return <div onClick={this.props.onClick || this.clickHandler}>...</div>;
}
});
and while using this in another component use it as below
...........
handler: function() {
// write your logic
},
render {
var self = this;
return (<MySampleComponent onClick={self.handler} />);
}
......

Resources