Create component with state:
class MyComponenth extends React.Component
{
constructor( props )
{
super( props );
this.state = {
MyStateVariable: "initial value",
...
};
}
Best way to bind events to class in ES6:
class MyComponent extends React.Component
{
_handleTouchTap = ( event, item ) =>
{
...
};
render( )
{
return <RaisedButton label="OK" onTouchTap={ this._handleTouchTap } />;
}
}
Creating a component only when a condition is satisfied. In the example when the number of completed ToDos is greater than zero, a touchable highlight with button to clear completed is displayed:
<div>
...
{ numCompletedTodos > 0 &&
<TouchableHighlight onPress={ this._handleRemoveCompletedTodosPress }>
<Text>Clear completed</Text>
</TouchableHighlight>
}
...
</div>
Link to a new location within the app using React Router:
class MyComponent extends React.Component
{
_GoToLocation = ( event, item ) =>
{
this.context.router.push( '/my/new/location' );
};
render( )
{
return <RaisedButton label="Go To New Location" onTouchTap={ this._GoToLocation } />;
}
}
MyComponent.contextTypes = {
router: React.PropTypes.object.isRequired,
};
Create a controlled text box with value in state:
class MyComponentWithTextField extends React.Component
{
constructor( props )
{
super( props );
this.state = {
MyTextBoxValue: 'initial value',
};
}
_handle_onChange_MyTextBox = ( event ) =>
{
this.setState( { MyTextBoxValue: event.target.value } );
};
render( )
{
return(
<div>
<TextField
value={ this.state.MyTextBoxValue }
onChange={ this._handle_onChange_MyTextBox }
/>
</div>
);
}
}
const resolvePromise = ( promise, callback ) => {
if( callback )
promise.then( value => callback( null, value ), callback )
return promise
}
const somethingAsync = ( a, b, c, callback ) =>
resolvePromise(
doSomethingAsync( a, b, c ), // Can be any promise-only API
callback
)
// Now use promises:
somethingAsync( a, b, c ).then( value => {
// Next step
}, error => {
// Error handling
} )
// Or call backs:
somethingAsync( a, b, c, ( error, value ) => {
// One function to handle both success and error.
} )
Source: resolvePromise.js.