class Example extends Component {
state = {
inputValue: '',
};
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value,
});
};
handleSubmit = e => {
e.preventDefault();
// получить состояние формы можно обратившись к this.state
};
render() {
const { inputValue } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<input
name="inputValue"
value={inputValue}
onChange={this.handleChange}
/>
...
</form>
);
}
class Example extends Component {
state = {
eventsList,
selectedEvent,
};
handleSelectEvent(event) {
this.setState({ selectedEvent: event });
}
render() {
const { eventsList, selectedEvent } = this.state;
return (
<Wrapper>
{selectedEvent && <EventDetails event={selectedEvent} />}
<ul>
{eventsList.map(event => (
<li
key={event.id}
onClick={() => this.handleSelectEvent(event)}
>
{event.name}
</li>
))}
</ul>
</Wrapper>
);
}
}
<BrowserRouter>
<App />
</BrowserRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/events" component={EventsList} />
<Route path="/event/:id" component={EventDetails} />
</Switch>
class EventsList extends Component {
state = {
eventsList,
};
render() {
const { eventsList } = this.state;
return (
<Wrapper>
<ul>
{eventsList.map(event => (
<li key={event.id}>
<Link to={`/event/${event.id}`}>{event.name}</Link>
</li>
))}
</ul>
</Wrapper>
);
}
}
class EventsList extends Component {
componentDidMount() {
const elementId = this.props.match.params.id;
}
render() {
...
}
}
const PrivateRoute = ({ component: Component, isAuth, ...rest }) => (
<Route {...rest} render={props => (isAuth
? <Component {...props} />
: <Redirect to='/login' />
)}
/>
);
const mapStateToProps = state => ({
isAuth: state.isAuth,
});
const mapDispatchToProps = {
authenticated,
};
export default connect(mapStateToProps, mapDispatchToProps)(PrivateRoute);
grafik.forEach(elem => {
elem.attr = attr;
});
grafik.forEach(elem => {
elem.attr = attr.map(el => ({ ...el }));
});
grafik.forEach(elem => {
elem.attr = attr.map(el => Object.assign({}, el));
});
this.setState(prevState => ({
tasks: [
...prevState.tasks,
{ content, comments: [], active: true},
],
}));
constructor(props) {
super(props);
this.onAddItem = this.onAddItem.bind(this);
}
onAddItem = content => {
// some stuff
};
class Example extends Component {
state = {
inputValue: '',
};
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value,
});
};
render() {
const { inputValue } = this.state;
return (
<Wrapper>
<input
name="inputValue"
value={inputValue}
onChange={this.handleChange}
/>
...
</Wrapper>
);
}
class Parent {
onNoteDelete = note => {
// some stuff
};
}
render() {
const { notes, onNoteDelete } = this.props;
return(
<div className="notes-grid" ref="grid">
{notes.map(note => (
<Note
key={note.id}
color={note.color}
onDelete={() => onNoteDelete(note)}
>
{note.text}
</Note>
))}
</div>
)
}
const formData = new FormData();
formData.append('file', someFile);
axios.post('/uploadFile', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
import React from 'react';
export default Task;
constructor(props) {
super(props);
this.state = {
isOpened: false,
};
this.clickHandler = this.clickHandler.bind(this);
}
clickHandler = e => {
// your stuff
};
this.setState(prevState => ({
isOpened: !prevState.isOpened,
}));
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
[
<li key="1">1</li>,
<li key="2">2</li>,
<li key="3">3</li>,
<li key="4">4</li>,
<li key="5">5</li>,
]
<ul>
{listItems}
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
const initialState: {
entities: {}.
isLoading: {
'ALL': false,
},
isError: {
'ALL': false,
}
}
const someEntityReduser = (state = initalState, action) => {
const { type, payload } = action;
switch (type) {
case GET_ALL_ENTITIES_REQUEST:
return {
...state,
isLoading: {
...state.isLoading,
'ALL': true,
},
isError: {
...state.isError,
'ALL': false,
},
};
case GET_ALL_ENTITIES_SUCCESS:
return {
...state,
entities: payload, // либо нормализация если приходят массивом
isLoading: {
...state.isLoading,
'ALL': false,
},
};
case UPDATE_ENTITY_REQUEST:
return {
...state,
isLoading: {
...state.isLoading,
[payload.id]: true,
},
isError: {
...state.isError,
[payload.id]: false,
},
};
case UPDATE_ENTITY_SUCCESS:
return {
...state,
entities: {
...state.entities,
[payload.id]: payload,
},
isLoading: {
...state.isLoading,
[payload.id]: false,
},
};
/* other cases */
}
}
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
const isVisited = localStorage.getItem("isVisited");
if (!isVisited) {
localStorage.setItem("isVisited", true);
}
class Home extends Component {
...
render() {
if (!isVisited) return <Redirect to="/nobel-laureates" />
...
}
}
Cannot assign to read only property
class Example extends Component {
state = {
inputValue: '',
};
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value,
});
};
render() {
const { inputValue } = this.state;
return (
<Wrapper>
<input
name="inputValue"
value={inputValue}
onChange={this.handleChange}
/>
...
</Wrapper>
);
}
this.setState({ ... }, () => this.getStateValues());
handleChange = ev => {
const { name, value } = ev.target;
const symbols = split('')(value);
const result = filter(i => characterVerification(i), symbols);
this.setState({
[name]: join('')(result)
}, () => this.getStateValues(),
);
};
constructor(props) {
super(props);
this.state = props.params;
this.onFieldChange = this.onFieldChange.bind(this); // тут
}
renderSingleValue(data = {}) {
...
let self = this; // бессмысленно
return (
<input type="text"
...
onChange={self.onFieldChange}
...
/>
);
}
constructor() {
const self = this;
node.addEventListener('click', function() {
self.handleEvent(); // сработает, так как функция вызывается на self
});
}
constructor() {
const self = this;
node.addEventListener('click', self.handleEvent); // не сработает, функция передается
// в колбек обработчика события
} // и не будет вызываться на self
class Example extends Component {
state = {
inputValue: '',
};
handleChange = e => { // arrow class field function биндится на контекст экземпляра
const { name, value } = e.target;
this.setState({
[name]: value,
});
};
render() {
const { inputValue } = this.state;
return (
<Wrapper>
<input
name="inputValue"
value={inputValue}
onChange={this.handleChange}
/>
...
</Wrapper>
);
}
}
class Example extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
const { name, value } = e.target;
this.setState({
[name]: value,
});
}
render() {
const { inputValue } = this.state;
return (
<Wrapper>
<input
name="inputValue"
value={inputValue}
onChange={this.handleChange}
/>
...
</Wrapper>
);
}
}
handleChange = value => {
const { name, onChange } = this.props;
const fakeEvent = { target: { name, value } };
onChange(fakeEvent);
};
state = { ...prevState, ...newState };
this.setState(prevState => ({
some_data: {
...prevState.some_data,
...input,
},
});
export const renderNotes = (user , users) => dispatch => {
Object.keys(users).forEach(async element => {
if (user === users[element].login) {
const elements = await fire.database().ref('users/' + element + '/notes/');
return dispatch({
type: RENDER_NOTES,
payload: elements,
});
}
})
};
const srcArray = [ 0.134555, 0.294587, 0.570858];
const mappedArray = srcArray.map(el => (el * 100).toFixed(1) + '%');
console.log(mappedArray);
// => ["13.5%", "29.5%", "57.1%"]
submitBalance = () => {
// your stuff
};
constructor(props) {
super(props);
this.submitBalance.bind(this);
}
onClick={e => this.submitBalance(someArg, e)}