Skip to content

Instantly share code, notes, and snippets.

@jungchris
Last active December 10, 2016 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jungchris/f767486f8bf8054e384617ffd930622e to your computer and use it in GitHub Desktop.
Save jungchris/f767486f8bf8054e384617ffd930622e to your computer and use it in GitHub Desktop.
Creating Random React Components
import React from 'react';
import Child from './Child';
import Child2 from './Child2';
// const App = () => <h1>ReactDOM</h1>
// class App extends React.Component {
// render() {
// return <h1>Reactly</h1>
// }
// }
// This is the source doc for this project:
// https://facebook.github.io/react/docs/react-component.html
class AppBeta extends React.Component {
constructor() {
// called when an instance of a component is being created and inserted into the DOM
super();
this.state = {
txt: 'AppBeta txt',
}
}
// update is not a native function
update(e) {
this.setState({txt: e.target.value})
}
// component reference: https://facebook.github.io/react/docs/react-component.html
componentWillMount() {
// called when an instance of a component is being created and inserted into the DOM
// is invoked immediately before mounting occurs. It is called before render()
console.log('componentWillMount');
}
componentDidMount() {
// called when an instance of a component is being created and inserted into the DOM
// a good place to instantiate the network request.
// Setting state in this method will trigger a re-rendering.
console.log('componentDidMount');
}
componentWillReceiveProps() {
// is invoked before a mounted component receives new props.
// If you need to update the state in response to prop changes (for example, to reset it),
// you may compare this.props and nextProps and perform state transitions using this.setState()
// in this method.
//
/// Note that React may call this method even if the props have not changed,
// so make sure to compare the current and next values if you only want to handle changes.
// This may occur when the parent component causes your component to re-render.
console.log('componentWillReceiveProps');
}
shouldComponentUpdate() {
// to let React know if a component's output is not affected by the current change
// in state or props. The default behavior is to re-render on every state change,
// and in the vast majority of cases you should rely on the default behavior.
console.log('shouldComponentUpdate');
return true;
}
componentWillUpdate() {
// is invoked immediately before rendering when new props or state are being received.
// use this as an opportunity to perform preparation before an update occurs.
// This method is not called for the initial render.
console.log('componentWillUpdate');
}
componentDidUpdate() {
// is invoked immediately after updating occurs. This method is not called for the initial render.
// Use this as an opportunity to operate on the DOM when the component has been updated.
// This is also a good place to do network requests as long as you compare the current props
// to previous props
// (e.g. a network request may not be necessary if the props have not changed).
console.log('componentDidUpdate');
}
componentWillUnmount() {
// componentWillUnmount() is invoked immediately before a component is unmounted and destroyed.
// Perform any necessary cleanup in this method, such as invalidating timers,
// canceling network requests, or cleaning up any DOM elements that were created in
// componentDidMount
console.log('componentWillUnmount');
}
render() {
// called when an instance of a component is being created and inserted into the DOM
// Refactored as 'Widget': <input type="text" onChange={this.update.bind(this)} />
return (
<div>
<h3>{this.props.introText}</h3>
<h3>{this.props.versionString}</h3>
<h3>{this.props.versionNumber}</h3>
<h3>Logged in user: {this.props.userName}</h3>
<Widget update={this.update.bind(this)} />
<Widget update={this.update.bind(this)} />
<Button>Submit <Heart /></Button>
<h3>{this.state.txt}</h3>
<Child childName="AppBeta childname: " textTyped={this.state.txt} />
<Child2 />
</div>
)
}
}
AppBeta.propTypes = {
introText: React.PropTypes.string,
versionString: React.PropTypes.string,
versionNumber: React.PropTypes.number,
userName: React.PropTypes.string,
}
AppBeta.defaultProps = {
introText: "Loading beta ...",
}
// const App = () => <h3>No state - Beta version</h3>
// not working: <h3>{this.props.txt}</h3>
// const AppBeta = () => (
// <div>
// <h3>Beta Version</h3>
// <h3>Stateless</h3>
// </div>
// )
class Heart extends React.Component {
render() {
return <span>&hearts;</span>
}
}
const Widget = (props) => <input type="text" onChange={props.update} />
const Button = (props) => <button>{props.children}</button>
export default AppBeta
import React from 'react';
// this class uses react-fetch to connect with openweathermap
// import FetchData from './FetchData';
import FetchJSON from './FetchJSON';
// stateless component
const Title = (props) => <h3>Child stateless Title props.text: {props.text}</h3>
// custom validation method ... more thab isrequired
Title.propTypes = {
text(props, propName, component) {
if (!(propName in props)) {
return new Error('missing {propName}')
}
if (props[propName].length < 4) {
return new Error('{propName} was too short')
}
}
}
class Child extends React.Component {
// component reference: https://facebook.github.io/react/docs/react-component.html
componentWillMount() {
// called when an instance of a component is being created and inserted into the DOM
// is invoked immediately before mounting occurs. It is called before render()
console.log('child componentWillMount');
}
componentDidMount() {
// called when an instance of a component is being created and inserted into the DOM
// a good place to instantiate the network request.
// Setting state in this method will trigger a re-rendering.
console.log('child componentDidMount');
}
componentWillReceiveProps() {
/// Note that React may call this method even if the props have not changed,
// so make sure to compare the current and next values if you only want to handle changes.
// This may occur when the parent component causes your component to re-render.
console.log('child componentWillReceiveProps');
Title.text = "a-b-c"
}
shouldComponentUpdate() {
// to let React know if a component's output is not affected by the current change
// in state or props. The default behavior is to re-render on every state change,
// and in the vast majority of cases you should rely on the default behavior.
console.log('child shouldComponentUpdate:');
// console.log('child shouldComponentUpdate:' {this.props.textTyped});
// if (this.props.textTyped==="b") {
// return false;
// } else {
// return true;
// }
// overriding to not update the child
return true;
}
componentWillUpdate() {
// is invoked immediately before rendering when new props or state are being received.
// use this as an opportunity to perform preparation before an update occurs.
// This method is not called for the initial render.
console.log('child componentWillUpdate');
}
componentDidUpdate() {
// is invoked immediately after updating occurs. This method is not called for the initial render.
// Use this as an opportunity to operate on the DOM when the component has been updated.
// This is also a good place to do network requests as long as you compare the current props
// to previous props
// (e.g. a network request may not be necessary if the props have not changed).
console.log('child componentDidUpdate');
}
componentWillUnmount() {
// componentWillUnmount() is invoked immediately before a component is unmounted and destroyed.
// Perform any necessary cleanup in this method, such as invalidating timers,
// canceling network requests, or cleaning up any DOM elements that were created in
// componentDidMount
console.log('child componentWillUnmount');
}
render() {
return (
<div>
<h3>{this.props.childName} {this.props.textTyped}</h3>
<h3>----</h3>
<Title text="Fetching:" />
<FetchJSON />
</div>
)
}
}
// const App = () => <h3>Stateless</h3>
export default Child
import React from 'react';
class Child2 extends React.Component {
constructor() {
super();
this.state = {currentEvent: '-*-'}
this.update = this.update.bind(this)
this.updatePaste = this.updatePaste.bind(this)
}
update(e) {
console.log('Child2 update()');
this.setState({currentEvent: e.type})
}
// just for fun, another action on paste
// If you neglect to bind in the constructor you will get this error:
// Uncaught TypeError: Cannot read property 'setState' of null
updatePaste(e) {
console.log('Child2 updatePaste()');
this.setState({currentEvent: e.type})
}
// and now an unbound function
// obviously you don't need to bind in the constructor if not doing anything
updateCut(e) {
console.log('Child2 updateCut');
}
// component reference: https://facebook.github.io/react/docs/react-component.html
componentWillMount() {
// called when an instance of a component is being created and inserted into the DOM
// is invoked immediately before mounting occurs. It is called before render()
console.log('Child2 componentWillMount');
}
componentDidMount() {
// called when an instance of a component is being created and inserted into the DOM
// a good place to instantiate the network request.
// Setting state in this method will trigger a re-rendering.
console.log('Child2 componentDidMount');
}
componentWillReceiveProps() {
/// Note that React may call this method even if the props have not changed,
// so make sure to compare the current and next values if you only want to handle changes.
// This may occur when the parent component causes your component to re-render.
console.log('Child2 componentWillReceiveProps');
}
shouldComponentUpdate() {
// to let React know if a component's output is not affected by the current change
// in state or props. The default behavior is to re-render on every state change,
// and in the vast majority of cases you should rely on the default behavior.
console.log('Child2 shouldComponentUpdate:');
// overriding to not update the Child2
return true;
}
componentWillUpdate() {
// is invoked immediately before rendering when new props or state are being received.
// use this as an opportunity to perform preparation before an update occurs.
// This method is not called for the initial render.
console.log('Child2 componentWillUpdate');
}
componentDidUpdate() {
// is invoked immediately after updating occurs. This method is not called for the initial render.
// Use this as an opportunity to operate on the DOM when the component has been updated.
// This is also a good place to do network requests as long as you compare the current props
// to previous props
// (e.g. a network request may not be necessary if the props have not changed).
console.log('Child2 componentDidUpdate');
}
componentWillUnmount() {
// componentWillUnmount() is invoked immediately before a component is unmounted and destroyed.
// Perform any necessary cleanup in this method, such as invalidating timers,
// canceling network requests, or cleaning up any DOM elements that were created in
// componentDidMount
console.log('Child2 componentWillUnmount');
}
render() {
return (
<div>
<textarea
onKeyPress={this.update}
onCopy={this.update}
onCut={this.updateCut}
onPaste={this.updatePaste}
cols="30"
rows="3" />
<h3>{this.state.currentEvent}</h3>
</div>
)
}
}
export default Child2
// Need to resolve:
// Uncaught Error: _registerComponent(...): Target container is not a DOM element.
//
import React from 'react';
import ReactDOM from 'react-dom';
class Child3 extends React.Component {
constructor() {
super();
this.state = {val: 0}
this.update = this.update.bind(this)
}
update() {
console.log('Child3 updating');
this.setState({val: this.state.val + 1})
}
componentWillUnmount() {
console.log('componentWillUnmount');
}
render() {
console.log('rendering');
return <button onClick={this.update}>{this.state.val}</button>
}
}
class Wrapper extends React.Component {
mount() {
ReactDOM.render(<Child3 />, document.getElementById('a'))
}
unmount() {
ReactDOM.unmountComponentAtNode(document.getElementById('a'))
}
render() {
return (
<div>
<button onClick={this.mount.bind(this)}>Mount</button>
<button onClick={this.unmount.bind(this)}>UnMount</button>
</div>
)
}
}
// exporting Wrapper instead of Child3 will allow wrapper to render app
export default Wrapper
// export default Child3
import React from 'react';
import ShowJSON from './ShowJSON';
// global variables
// stateless component
// const Reply = (props) => {props.data}
// // custom validation method ... more thab isrequired
// Reply.propTypes = {
// data(props, propData, component) {
// if (!(propData in props)) {
// return new Error('missing {propData}')
// }
// if (props[propName].length < 4) {
// return new Error('{propData} was too short')
// }
// }
// }
// I'm having trouble assigning the result to a global variable
// var responseFromCall;
class FetchJSON extends React.Component {
constructor() {
super();
this.state={currentData:''}
this.updateJSON=this.updateJSON.bind(this)
}
// https://facebook.github.io/react-native/docs/network.html
// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
updateJSON(e) {
console.log('FetchJSON updateJSON()');
this.setState({currentData:e})
}
// <ShowJSON userToken={101} jsonData={this.responseFromCall} />
componentDidMount() {
// called when an instance of a component is being created and inserted into the DOM
// a good place to instantiate the network request.
// Setting state in this method will trigger a re-rendering.
console.log('FetchJSON componentDidMount');
if (self.fetch) {
console.log('fetch supported')
// using fetch as defined by getMovies
var responseFromCall = this.getMoviesFromApiAsync();
console.log(responseFromCall);
} else {
console.log('fetch unsupported')
}
}
componentWillUnmount() {
console.log('FetchJSON componentWillUnmount');
}
// component reference: https://facebook.github.io/react/docs/react-component.html
componentWillMount() {
// called when an instance of a component is being created and inserted into the DOM
// is invoked immediately before mounting occurs. It is called before render()
console.log('FetchJSON componentWillMount');
}
componentWillReceiveProps() {
/// Note that React may call this method even if the props have not changed,
// so make sure to compare the current and next values if you only want to handle changes.
// This may occur when the parent component causes your component to re-render.
console.log('FetchJSON componentWillReceiveProps');
}
shouldComponentUpdate() {
// to let React know if a component's output is not affected by the current change
// in state or props. The default behavior is to re-render on every state change,
// and in the vast majority of cases you should rely on the default behavior.
console.log('FetchJSON shouldComponentUpdate:');
return true;
}
componentWillUpdate() {
// is invoked immediately before rendering when new props or state are being received.
// use this as an opportunity to perform preparation before an update occurs.
// This method is not called for the initial render.
console.log('FetchJSON componentWillUpdate');
}
componentDidUpdate() {
// is invoked immediately after updating occurs. This method is not called for the initial render.
// Use this as an opportunity to operate on the DOM when the component has been updated.
// This is also a good place to do network requests as long as you compare the current props
// to previous props
// (e.g. a network request may not be necessary if the props have not changed).
console.log('FetchJSON componentDidUpdate');
}
// url="api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=c6af0cd6ffa8c9a72ae6bc720aac27c7">
render() {
return (
<div>
<h3>Making JSON call</h3>
<ShowJSON userToken={871263} jsonResult={this.responseFromCall} />
</div>
)
}
}
export default FetchJSON
import React from 'react';
import ReactDOM from 'react-dom';
import App from './AppBeta';
// this renders the DOM by pulling from App.js
ReactDOM.render(
<App introText="Alpha app" versionString="Version is:" versionNumber={0.2} userName="chris" />,
document.getElementById('root')
);
import React from 'react';
class ShowJSON extends React.Component {
componentDidMount() {
// called when an instance of a component is being created and inserted into the DOM
// a good place to instantiate the network request.
// Setting state in this method will trigger a re-rendering.
console.log('ShowJSON componentDidMount');
}
componentWillUnmount() {
console.log('ShowJSON componentWillMount');
}
// component reference: https://facebook.github.io/react/docs/react-component.html
componentWillMount() {
// called when an instance of a component is being created and inserted into the DOM
// is invoked immediately before mounting occurs. It is called before render()
console.log('ShowJSON componentWillMount');
}
componentWillReceiveProps() {
/// Note that React may call this method even if the props have not changed,
// so make sure to compare the current and next values if you only want to handle changes.
// This may occur when the parent component causes your component to re-render.
console.log('ShowJSON componentWillReceiveProps');
}
shouldComponentUpdate() {
// to let React know if a component's output is not affected by the current change
// in state or props. The default behavior is to re-render on every state change,
// and in the vast majority of cases you should rely on the default behavior.
console.log('ShowJSON shouldComponentUpdate:');
return true;
}
componentWillUpdate() {
// is invoked immediately before rendering when new props or state are being received.
// use this as an opportunity to perform preparation before an update occurs.
// This method is not called for the initial render.
console.log('ShowJSON componentWillUpdate');
}
componentDidUpdate() {
// is invoked immediately after updating occurs. This method is not called for the initial render.
// Use this as an opportunity to operate on the DOM when the component has been updated.
// This is also a good place to do network requests as long as you compare the current props
// to previous props
// (e.g. a network request may not be necessary if the props have not changed).
console.log('ShowJSON componentDidUpdate');
}
render() {
return (
<div>
<h3>todo: Show results here</h3>
<h3>user token: {this.props.userToken}</h3>
<h3>json: {this.props.jsonResult}</h3>
</div>
)
}
}
export default ShowJSON
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment