React es6 snippets
componentWillReceiveProps(nextProps) {
if (nextProps.theme !== this.props.theme) {
this.setStyleToRedactor(nextProps.theme);
}
}
example
hocuse
state = this.state;
state[prop] = value;
this.changeState(state);
//this will changed currentItem and item in the list which is linked to this currentItem
// use find() to find item
state = {
currentItem: {id:1, name: Vasya},
list: [{id:1, name: Vasya}, {id:2, name: Katya}]
}
https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e
const Connect = ComposedComponent =>
class extends React.Component {
constructor() {
super()
this.state = { name: "" }
}
componentDidMount() {
// this would fetch or connect to a store
this.setState({ name: "Michael" })
}
render() {
return (
<ComposedComponent
{...this.props}
name={this.state.name}
/>
)
}
}
// 2
function ppHOC(WrappedComponent) {
return class PP extends React.Component {
render() {
const newProps = {
user: currentLoggedInUser
}
return <WrappedComponent {...this.props} {...newProps}/>
}
}
}
// 3
// In the following example we explore how to access instance methods and the instance itself of the WrappedComponent via refs
function refsHOC(WrappedComponent) {
return class RefsHOC extends React.Component {
proc(wrappedComponentInstance) {
wrappedComponentInstance.method()
}
render() {
const props = Object.assign({}, this.props, {ref: this.proc.bind(this)})
return <WrappedComponent {...props}/>
}
}
}
//4
// Inheritance Inversion allows the HOC to have access to the WrappedComponent instance via this, which means it has access to the state, props, component lifecycle hooks and the render method.
// Inheritance Inversion
function iiHOC(WrappedComponent) {
return class Enhancer extends WrappedComponent {
render() {
return super.render()
}
}
}
// 4
function iiHOC(WrappedComponent) {
return class Enhancer extends WrappedComponent {
render() {
if (this.props.loggedIn) {
return super.render()
} else {
return null
}
}
}
}
// pass props to children
{React.cloneElement(this.props.children, { loggedIn: this.state.loggedIn })}
5. instead of HOC
// ScrollWatch - compose any component(s) that need
// to make use of the current 'x' and 'y' scroll position.
import React, { Component } from 'react';
class ScrollWatch extends Component {
state = { x: 0, y: 0 };
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
handleScroll = e => {
this.setState({
x: window.scrollX,
y: window.scrollY
})
};
render() {
const { x, y } = this.state;
return this.props.render(x,y);
}
}
// Component to display and 'x' and 'y'
const ShowPosition = ({x, y}) => (
<p style={{ position: 'fixed', top: 0, left: 0, padding: '5px' }}>
x: {x}, y: {y}
</p>
);
render(
<div>
<ScrollWatch render={
(x,y) => (
<ShowPosition x={x} y={y} />
)
}
/>
</div>
, document.querySelector('#root'));
// example of HOC fetch data
https://codepen.io/alisd23/pen/gwArYrhttp://www.dofactory.com/javascript/factory-method-design-pattern
games.forEach(function (item, index) {
items.push()
});
for (let i = 0; i < deviders.length; i++)
{
console.log("deviders length");
console.log(deviders[i]);
}
//from array to string
arr = ['bla', 'has']
var str = arr.join(';'); // ; - разделитель
*************************************************
// добавить в массив элемент без мутации
[...list, 0] // analog to list.push(0)
// ********************************************
REMOVE FROM ARRAY
index - index of item in array
list.slice(0, index).concat(list.slice(index + 1))
[...list.slice(0, index), ...list.slice(index+ 1)]
*******************************************************
CHANGE ITEM VALUE IN ARRAY
mutating style: list[index] ++ ;
analog: [...list.slice(0, index) , list[index] + 1, ...list.slice(index+1)]import { combineReducers } from 'redux'
import { createAction, handleActions } from 'redux-actions'
const authorFetched = createAction('AUTHOR_FETCHED')
const bookFetched = createAction('BOOK_FETCHED')
const authorReducer = handleActions({
AUTHOR_FETCHED: (state, action) => {
const author = action.payload
return Object.assign({}, state, { [author.id]: author })
},
// opportunistically grab the author from a book fetch
BOOK_FETCHED: (state, action) => {
const book = action.payload
const { author } = book
return Object.assign({}, state, { [author.id]: author })
},
}, {
})
const bookReducer = handleActions({
// opportunistically grab the books from an author fetch
AUTHOR_FETCHED: (state, action) => {
const author = action.payload
const { books } = author
return Object.assign({}, state, books)
},
BOOK_FETCHED: (state, action) => {
const book = action.payload
return Object.assign({}, state.books, { [book.id]: book })
},
}, {
})
export const authorSelector = id => state => state.literary.authors[id]
export const bookSelector = id => state => state.literary.books[id]
export default combineReducers({
literary: combineReducers({
authors: authorReducer,
books: bookReducer,
}),
otherStuff: otherReducer,
})import React, { Component } from 'react'
import Icon from '../ui/icon'
import {c, isValue, preventEvent} from '../functions'
import * as F from '../functions'
import { Link } from 'react-router'
import {MAIN_COLOR} from '../style'
// poppup
onClickHandler(e) {
ReactDOM.render(
<PopupBody isOpen ={true} >Bla</PopupBody>,
document.getElementById('popup'));
}document.getElementByClass("stopButton");
document.querySelector("img[alt = 'beaconsMap']");
// refs
let progressBar = this.refs.progress;
<Progress ref="progress" />
// end refs
// reload page
location.reload();
// ownProps - thing ownProps gives access to the properties passed into the FilterLink. It is related to the presentational component Link in that it helps to generate the properties of Link
function mapStateToProps(state, ownProps) {
}
// замена mapDispatchToProps
function mapDispatchToProps(dispatch) {
return {
setScore: (score) => dispatch(setScore(score)),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(GameContainer)
заменить на
export default connect(mapStateToProps, {setScore: setScore})(GameContainer)
// function inside function
return b(); calls the function b(), and returns its result.
return b; returns a reference to the function b, which you can store in a variable to call later.
function d() {
function e() {
alert('E');
}
return e;
}
d()();
//alerts 'E'
демонстрация замыкания
function counter() {
var count = 0;
return function() {
alert(count++);
}
}
var count = counter();
count();
count();
count();
// args validation
function requered (i)
throw new error ("Missing " i);
function foo (a = requered(i))
return a + 1
// тоже самое с декоратором
@requered('arg1')
function foo (arg1) {
return arg1 + 1
}
if (isValue(array))
{
console.log("array not null");
result = array.find(function (value, index) {
return value === role;
});
}
result = isValue(result) ? true : false;e<Icon icon="fa fa-play"/>
import { Link } from 'react-router'
<Link to={'/game/:id' + item.id}>Play</Link>
const { players = [], loading = false } = this.props;