Write first component
// MyComponent.js
import React from 'react'
class MyClass extends React.Component {
render (
return(
<div></div>
)
)
}
export default MyClass
Render it on the HTML
// index.js
import React from 'react'
import { render } from 'react-dom'
import MyComponent from './MyComponent'
render(<StorePicker />, document.getElementById('main'))
Can also be included with
import './style.css'
Processed by Webpack
add attributes to components
<Component myProp='data' myObj={JSObj} onClick={doSth}>
access variables via props
class MyComponent extends React.Component {
render(
return(
<p>{this.props.myProp}</p>
<p>{this.props.myObj}</p>
<p>{this.props.onClick}</p>
)
)
}
replace class MyClass ... with
const MyFunction = (props) => {
return(
<p>{props.myProp}</p>
<p>{props.myObj}</p>
<p>{props.onClick}</p>
)
}
Don't render component directly, but router
// index.js
import { BrowserRouter, Match, Miss } from 'react-router'
const Root = () => {
return (
<BrowserRouter>
<Match exactly pattern='/' component={MyComponent}/>
<Match pattern='/mystuff/:myarg' component={MyStuff} />
<Miss component={OhNo} />
</BrowserRouter>
)
}
render(<Root />, document.getElementById('main'))
Reference form elements as follows:
<input type='text' ref={(input)=>{ this.whateverName = input }}
now you can access it through 'this'.
You have to bind 'this' in functions other than render
See this example with event handling:
class MyClass extends React.Component {
constructor () {
super()
this.myFunction = this.myFunction.bind('this')
}
myFunction (event) {
this.nowAvailable('!!!')
event.preventDefault()
}
render () {
return (
<p onClick={this.myFunction.bind(this)}>test</p>
<p onClick={(e) => {this.myFunction(e)}}>test</p>
or
<p onClick={this.myFunction}>test</p> Needs constructor hack
)
}
}