import React from "react";
import { render } from "react-dom";
import "./index.css";
const data = [
{ index: 0, product: "Bread", category: "Food", price: 1 },
{
index: 1,
product: 'F. Dostoyevsky "Crime and Punishment"',
category: "Books",
price: 8
},
{ index: 2, product: "iPhone", category: "Electronics", price: 699 },
{ index: 3, product: "Milk", category: "Food", price: 2 },
{ index: 4, product: "TV", category: "Electronics", price: 1099 }
];
class TableRow extends React.Component {
render() {
return (
<tr>
<td>{this.props.index}</td>
<td>{this.props.product}</td>
<td>{this.props.category}</td>
<td>
{"$"}
{this.props.price}
</td>
</tr>
);
}
}
class Table extends React.Component {
constructor(props) {
super(props);
this.state = {
index: true,
product: true,
category: true,
price: true,
data: props.data
};
}
sortByIndex() {
var getIndex = !this.state.index;
var data = this.state.data;
data.sort((a, b) => {
if (!getIndex) {
return b.index - a.index;
} else {
return a.index - b.index;
}
});
this.setState({ data, index: getIndex });
}
sortByProductName() {
var getProduct = !this.state.product;
var data = this.state.data;
data.sort((a, b) => {
if (!getProduct) {
return b.product > a.product;
} else {
return a.product > b.product;
}
});
this.setState({ data, product: getProduct });
}
sortByCategory() {
var getCategory = !this.state.category;
var data = this.state.data;
data.sort((a, b) => {
if (!getCategory) {
return b.category > a.category;
} else {
return a.category > b.category;
}
});
this.setState({ data, category: getCategory });
}
sortByPrice() {
var getPrice = !this.state.price;
var data = this.state.data;
data.sort((a, b) => {
if (!getPrice) {
return b.price - a.price;
} else {
return a.price - b.price;
}
});
this.setState({ data, price: getPrice });
}
render() {
return (
<table className="table">
<tr>
<th onClick={this.sortByIndex.bind(this)}>
Index <i className={this.state.index ? "fa fa-caret-up" : "fa fa-caret-down"} aria-hidden="true" />{" "}
</th>
<th onClick={this.sortByProductName.bind(this)}>
Product <i className={this.state.product ? "fa fa-caret-up" : "fa fa-caret-down"} aria-hidden="true" />{" "}
</th>
<th onClick={this.sortByCategory.bind(this)}>
Category <i className={this.state.category ? "fa fa-caret-up" : "fa fa-caret-down"} aria-hidden="true" />{" "}
</th>
<th onClick={this.sortByPrice.bind(this)}>
Price <i className={this.state.price ? "fa fa-caret-up" : "fa fa-caret-down"} aria-hidden="true" />{" "}
</th>
</tr>
<tbody>{this.state.data.map((element, i) => <TableRow key={Math.random()} index={element.index} product={element.product} category={element.category} price={element.price} />)}</tbody>
</table>
);
}
}
render(<Table data={data} />, document.getElementById("root"));
"use strict";
this.setState({
displayed: containerWidth <= 719 ? 1 : 3
});
<div className="post-item__buttons buttons-block">
<button
className="buttons-block__change"
onClick={this.props.onClickmodify}
data-id={this.props.dataID}
>
..
</button>
<button
className="buttons-block__delete"
onClick={this.props.onClickdelete}
data-id={this.props.dataID}
>
x
</button>
</div>;
...
modifyItem(e) {
let target = e.target;
let targetID = target.getAttribute('data-id');
console.log(targetID, 'target id');
this.props.modifyItemCallback(targetID);
}
deleteItem(e) {
let target = e.target;
let targetID = target.getAttribute('data-id');
fetch(`https://my-json-server.typicode.com/sergemin/render-list/posts/${targetID}`, {
method: 'DELETE'
})
.then(() => {
console.log(targetID);
this.props.deleteItemCallback(targetID)
})
.catch(error => console.log(error));
}
...
<Post
key={item.id}
dataID={item.id}
title={item.title}
content={item.body}
modifyItemCallback={(id) => console.log(id)}
deleteItemCallback={(id) => console.log(id)}
/>;
кстати очень хороший вопрос
используйте zeit/now с zeit/next.js
наверно слышали или пробовали
class App extends React.Component {
state = { arr: ["hello", "world", "wow", "react"] };
render() {
return (
<section>
{this.state.arr.map(v => (
<div className="row">
<div>element</div>
<div>element</div>
<div>element</div>
</div>
))}
</section>
);
}
}
ReactDOM.render(<App />, document.body);
deleteItem(event) {
const conf = confirm(`Are you sure?`);
let number = parseFloat(event.target.parentNode.getAttribute("data-key"));
let newTodos = this.state.todos;
if (conf) {
newTodos = newTodos.splice(newTodos.indexOf(number), 1);
this.setState({ todos: newTodos });
} else {
alert(`ok we won't delete it `);
}
}
а почему бы не падать index прямо из.map()
.было бы намного правильнее чем искать в атрибутах
React не рекомендуем вам хранить данные в DOM атрибутов. Даже если у вас есть, атрибуты данных, вероятно, являются более оптимальным подходом, но в большинстве случаев данные должны храниться в состояние компонента реагировать или внешние хранилища.
class Header extends React.Component {
render() {
const menu = {
home: "#home",
pricing: "#pricing",
"about us": "#about-us"
};
const navLinks = Object.keys(menu).map((key, item) => {
return (
<a href={"/" + menu[key]}>
{menu[key]}
</a>
);
});
return (
<nav>
{navLinks}
</nav>
);
}
}
ReactDOM.render(<Header />, document.body);