14
loading...
This website collects cookies to deliver better user experience
const element = React.createElement(
'div',
{id: 'login-btn'},
'Login'
)
{
type: 'div',
props: {
children: 'Login',
id: 'login-btn'
}
}
<div id='login-btn'>Login</div>
const Button = ({ onLogin }) =>
<div id={'login-btn'} onClick={onLogin}>Login</div>
const Button = ({ onLogin }) => React.createElement(
'div',
{ id: 'login-btn', onClick: onLogin },
'Login'
)
function Greeting({ message }) {
return <h1>{`Hello, ${message}`}</h1>
}
class Greeting extends React.Component {
render() {
return <h1>{`Hello, ${this.props.message}`}</h1>
}
}
class User extends React.Component {
constructor(props) {
super(props)
this.state = {
message: 'Welcome to React world'
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
)
}
}
Pass custom data to your component.
Trigger state changes.
Use via this.props.reactProp inside component render() method
<Element reactProp={'1'} />
props.reactProp
//Wrong
this.state.message = 'Hello world'
//Correct
this.setState({ message: 'Hello World' })
setState({ name: 'John' }, () => console.log('The name has updated and component re-rendered'))
<button onClick={activateLasers}>
<button onClick={activateLasers}>
<a href='#' onclick='console.log("The link was clicked."); return false;' />
function handleClick(event) {
event.preventDefault()
console.log('The link was clicked.')}
class Foo extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Click happened');
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}
handleClick = () => {
console.log('this is:', this)
}
<button onClick={this.handleClick}>
{'Click me'}
</button>
handleClick() {
console.log('Click happened');
}
render() {
return <button onClick={() => this.handleClick()}>Click Me</button>;
}
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)
Mounting: The component is ready to mount in the browser DOM. This phase covers initialization from constructor(), getDerivedStateFromProps(), render(), and componentDidMount() lifecycle methods.
Updating: In this phase, the component gets updated in two ways, sending the new props and updating the state either from setState() or forceUpdate(). This phase covers getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods.
Unmounting: In this last phase, the component is not needed and gets unmounted from the browser DOM. This phase includes the componentWillUnmount() lifecycle method.
Render The component will render without any side effects. This applies for Pure components and in this phase, React can pause, abort, or restart the render.
Pre-commit Before the component actually applies the changes to the DOM, there is a moment that allows React to read from the DOM through the getSnapshotBeforeUpdate().
Commit React works with the DOM and executes the final lifecycles respectively componentDidMount() for mounting, componentDidUpdate() for updating, and componentWillUnmount() for unmounting.
ReactDOM.createPortal(child, container)
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
records: [],
inputValue: this.props.inputValue
};
}
render() {
return <div>{this.state.inputValue}</div>
}
}
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
record: []
}
}
render() {
return <div>{this.props.inputValue}</div>
}
}
import { withRouter } from 'react-router-dom' // this also works with 'react-router-native'
const Button = withRouter(({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
{'Click Me!'}
</button>
))
import { Route } from 'react-router-dom'
const Button = () => (
<Route render={({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
{'Click Me!'}
</button>
)} />
)
const Button = (props, context) => (
<button
type='button'
onClick={() => {
context.history.push('/new-location')
}} >
{'Click Me!'}
</button>
)
Button.contextTypes = {
history: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
})
}
const queryString = require('query-string');
const parsed = queryString.parse(props.location.search);
const params = new URLSearchParams(props.location.search)
const foo = params.get('name')
const getUserData = state => state.user.data
const mapDispatchToProps = (dispatch) => ({
action: () => dispatch(action())
})
const mapDispatchToProps = (dispatch) => ({
action: bindActionCreators(actioimport { ADD_TODO } from './actionTypes'
export default (state = [], action) => {
switch (action.type) {
case ADD_TODO:
return [
...state,
{
text: action.text,
completed: false
}
];
default:
return state
}
}
n, dispatch)
})
const mapDispatchToProps = { action }
function* fetchUserSaga(action) {
// `call` function accepts rest arguments, which will be passed to `api.fetchUser` function.
// Instructing middleware to call promise, it resolved value will be assigned to `userData` variable
const userData = yield call(api.fetchUser, action.userId)
// Instructing middleware to dispatch corresponding action.
yield put({
type: 'FETCH_USER_SUCCESS',
userData
})
}
const getUserData = state => state.user.data
<Mouse>
{mouse => (
<p>The mouse position is {mouse.x}, {mouse.y}</p>
)}</Mouse>children={mouse => (
<p>The mouse position is {mouse.x}, {mouse.y}</p>
)}/>
<<Mouse>
{mouse => (
<p>The mouse position is {mouse.x}, {mouse.y}</p>
)}</Mouse>
Mouse.propTypes = {
children: PropTypes.func.isRequired
};
function withMouse(Component) {
return class extends React.Component {
render() {
return (
<Mouse render={mouse => (
<Component {...this.props} mouse={mouse} />
)}/>
);
}
}
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
User Name:
<input
defaultValue="John"
type="text"
ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}