ReactJS - covering with '0' the blank spaces - javascript

I have this ReactJS App
See the app working
https://codepen.io/claudio-bitar/pen/VERORW
It returns a pagination with at maximum eight numbers per page.
Example:
I have ten numbers, so
Page one: 1, 2, 3, 4, 5, 6, 7, 8
page two: 9, 10
I would like to cover with '0' the blank numbers space until I reached 8 numbers. For example in the page two I would like to return:
9, 10, 0, 0, 0, 0, 0, 0
How can I solve it? Thank you
The App code:
class TodoApp extends React.Component {
constructor() {
super();
this.state = {
todos: {
"elements": ['1','2','3','4','5','6','7','8','9','10']
},
currentPage: 1,
todosPerPage: 8
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying current todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.elements.slice(indexOfFirstTodo, indexOfLastTodo);
const renderTodos = currentTodos.map((todo, index) => {
return <li key={index}>{todo}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.elements.length / todosPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
>
{number}
</li>
);
});
return (
<div>
<ul>
{renderTodos}
</ul>
<ul id="page-numbers">
{renderPageNumbers}
</ul>
</div>
);
}
}
ReactDOM.render(
<TodoApp />,
document.getElementById('app')
);

You could create a loop that will loop until currentTodos has todosPerPage elements in it and just push 0 until it does.
class TodoApp extends React.Component {
// ...
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying current todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.elements.slice(
indexOfFirstTodo,
indexOfLastTodo
);
while (currentTodos.length !== todosPerPage) {
currentTodos.push(0);
}
// ...
}
}
class TodoApp extends React.Component {
constructor() {
super();
this.state = {
todos: {
elements: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
},
currentPage: 1,
todosPerPage: 8
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying current todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.elements.slice(
indexOfFirstTodo,
indexOfLastTodo
);
while (currentTodos.length !== todosPerPage) {
currentTodos.push(0);
}
const renderTodos = currentTodos.map((todo, index) => {
return <li key={index}>{todo}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.elements.length / todosPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li key={number} id={number} onClick={this.handleClick}>
{number}
</li>
);
});
return (
<div>
<ul>{renderTodos}</ul>
<ul id="page-numbers">{renderPageNumbers}</ul>
</div>
);
}
}
ReactDOM.render(<TodoApp />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Related

How to reset interval and call api with interval in a function in react js

Hello I wanted to reset my set interval whenever my function is been called iam calling my interval in componentDidmount in react js and I want it to reset previous interval whenever that function is called iam also changing the value of api in that same function and now i want it to behave with the changes. The function is all three of the keyPressed Below is my code.
import React, { Component } from "react";
import { HotKeys } from "react-hotkeys";
import Axios from "axios";
class Test extends Component {
constructor(props) {
super(props);
this.state = {
seconds: 3,
color: null,
items: [],
currentItem: [],
index: 0
};
this.handleChange = this.handleChange.bind(this);
this.keyMap = {
DONT_APPLIES: ["a", "A"],
APPLIES: ["s", "S"],
STRONGLY_APPLIES: ["d", "D"]
};
this.handlers = {
DONT_APPLIES: e => {
this.keyPressed();
},
APPLIES: e => {
this.keyPressed1();
},
STRONGLY_APPLIES: e => {
this.keyPressed2();
}
};
}
keyPressed(e) {
const { index, items } = this.state;
const nextQuestion = index + 1;
this.setState({ currentItem: items[nextQuestion], index: nextQuestion });
console.log(this.state);
}
keyPressed1(e) {
const { index, items } = this.state;
const nextQuestion = index + 1;
this.setState({ currentItem: items[nextQuestion], index: nextQuestion });
console.log(this.state);
}
keyPressed2(e) {
const { index, items } = this.state;
const nextQuestion = index + 1;
this.setState({ currentItem: items[nextQuestion], index: nextQuestion });
console.log(this.state);
}
handleChangeColor = newColor => {
this.setState({
color: newColor
});
};
componentDidMount() {
this.myInterval = setInterval(() => {
const { seconds } = this.state;
if (seconds > 0) {
this.setState(({ seconds }) => ({
seconds: seconds - 1
}));
} else if (seconds == 0) {
return this.handleChangeColor("#840000");
}
}, 1000);
Axios.get("https://jsonplaceholder.typicode.com/users")
.then(response => {
console.log(response);
this.setState({
items: response.data.result.items,
currentItem: response.data.result.items[0],
index: 0
});
})
.catch(error => {
console.log(error);
});
}
componentWillUnmount() {
clearInterval(this.myInterval);
}
render() {
const { seconds } = this.state;
const timebox = {
width: "50px",
height: "20px"
};
const { currentItem } = this.state;
return (
<HotKeys keyMap={this.keyMap} handlers={this.handlers}>
<div id="wrapper" class="myleaty">
<div class="myleaty-holder">
<div class="container">
<div style={{ background: this.state.color }} class="myleaty-box">
<div style={timebox}>
<h2>{seconds}</h2>
</div>
<div class="logo">
<a href="#">
<img src="images/logo.png" alt="leaty" />
</a>
</div>
<p key={currentItem.id}>{currentItem.pqDetail}</p>
<div class="btn-row">
<button className="btn btn1">Does not Applies</button>
<button className="btn">Applies</button>
<button className="btn btn1">Strongly Applies</button>
</div>
</div>
</div>
</div>
</div>
</HotKeys>
);
}
}
export default Test;

Add items to page with localstorage

the array is stored in local storage by clicking on the “More” button 2 news is added to DOM
How should I implement this?
const ARR= [
{
id: 1,
Name: 'Name1',
text:'lorem ipsum'
},
{
id: 2,
Name: 'Name2',
text:'lorem ipsum'
},
{
id: 3,
Name: 'Name3',
text:'lorem ipsum'
},
{
id: 4,
Name: 'Name4',
text:'lorem ipsum'
},
];
10 obj
here we save the array in localStorage
and where to execute its JSON.parse (localStorage.getItem ('news')) and I don’t understand how to implement work with local storage by click
```
localStorage.setItem('news', JSON.stringify(ARR));
class NewsOne extends PureComponent {
constructor() {
super();
this.state = {
listItem: ARR,
formAdd: false,
};
this.createItem = this.createItem.bind(this);
this.updateItem = this.updateItem.bind(this);
this.removeItem = this.removeItem.bind(this);
this.addForm = this.addForm.bind(this);
}
updateItem(item) {
const { listItem } = this.state;
this.setState({
listItem: listItem.map(elem => (
elem.id === item.id ? item : elem
))
});
}
removeItem(itemId) {
const { listItem } = this.state;
this.setState({
listItem: listItem.filter(item => item.id !== itemId)
});
}
createItem(item) {
const { listItem } = this.state;
this.setState({
listItem: [item, ...listItem],
});
}
addForm() {
const { formAdd } = this.state;
this.setState({
formAdd: !formAdd,
})
}
render() {
const { listItem, formAdd } = this.state;
return(
<>
<div className="box">
<Title />
<List
data={listItem}
removeFromProps={this.removeItem}
updateFromProps={this.updateItem}
/>
</div>
<button className ="addnews" onClick = {this.addForm}>
Add
</button>
</>
);
}
}
A class that defaultly displays 2 elements on page.
I tried here to interact with the array from localStorage, but it fails
class List extends PureComponent {
constructor() {
super();
this.state = {
count: 2,
}
this.addObj = this.addObj.bind(this);
}
addObj() {
const { count } = this.state;
this.setState({
count: count + 2,
});
}
render() {
const { count } = this.state;
const { data } = this.props;
return(
<>
<ul>
{
data.slice(0, count).map(item => (
<>
<Item
key={item.id}
item={item}
/>
</>
))
}
</ul>
<button className ="addnews" onClick = {this.addObj}>
More
</button>
</>
);
}
}

ReactJS - Changing the color of the current number of the pagination

I have a pagination ReactJS App.
See the app link:
https://codepen.io/claudio-bitar/pen/VERORW
I would like to change the color of the current number of the pagination. For exemple the first page is shown so I want to change the color of number one, second, number two and etc...
The code:
class TodoApp extends React.Component {
constructor() {
super();
this.state = {
todos: {
"elements": ['a','b','c','d','e','f','g','h','i','j','k']
},
currentPage: 1,
todosPerPage: 3
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying current todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.elements.slice(indexOfFirstTodo, indexOfLastTodo);
const renderTodos = currentTodos.map((todo, index) => {
return <li key={index}>{todo}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.elements.length / todosPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
>
{number}
</li>
);
});
return (
<div>
<ul>
{renderTodos}
</ul>
<ul id="page-numbers">
{renderPageNumbers}
</ul>
</div>
);
}
}
ReactDOM.render(
<TodoApp />,
document.getElementById('app')
);
You need to give the <li> a classname dependeing on the current page number and provide a css class for it.
For example:
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
className={currentPage === number ? 'active' : ''}
>
{number}
</li>
);
});
This should result in a DOM node like either <li id="1" class="active">1</li> or <li id="1">1</li>

React JS - Transform a static pagination to dynamic from JSON

I have a ReactJS code below made for a SO user Piotr Berebecki. The code is working succefully It is a handle pagination returning items from an array. I want to do the same thing but returning data from JSON DB How can I do? How can I solve it? Thank you. Here is the app in the CodePen.
Here is My DB Json. I want only return the images (named as 'fotos'). It will replace the 'todos' in the array in the second code below
. Note: It must be made by Axios.
{
"interiores": [
{
"nome": "house 1",
"descricao": "This is the description of the house 1",
"fotos": [
"int_02", "int_02", "int_02", "int_02", "int_02"
]
}
]
}
Code:
import React, { Component } from 'react'
class Todo extends Component {
constructor() {
super();
this.state = {
todos: ['a','b','c','d','e','f','g','h','i','j','k'],
currentPage: 1,
todosPerPage: 3
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);
const renderTodos = currentTodos.map((todo, index) => {
return <li key={index}>{todo}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
>
{number}
</li>
);
});
return (
<div>
<ul>
{renderTodos}
</ul>
<ul id="page-numbers">
{renderPageNumbers}
</ul>
</div>
);
}
}
export default Todo;
It seems like you're asking how to handle the data once you've already made the call, this is how I think you should do it using componentDidMount I haven't tested it yet, but should give you a good starting point.
{
"interiores": [
{
"nome": "house 1",
"descricao": "This is the description of the house 1",
"fotos": [
"int_02", "int_02", "int_02", "int_02", "int_02"
]
}
]
}
import React, { Component } from 'react'
class Todo extends Component {
constructor() {
super();
this.state = {
todos: ['a','b','c','d','e','f','g','h','i','j','k'],
currentPage: 1,
todosPerPage: 3 ,
fotos: '',
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
async componentDidMount() {
//make call to database and set the db data to your state.
const dbData = axios.get('http://yourapi.com/todods')
.then(function (response) {
this.setState({fotos: response.data.interiores[0].fotos})
})
.catch(function (error) {
console.log('error:', error);
});
}
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);
const renderTodos = currentTodos.map((todo, index) => {
return <li key={index}>{todo}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
>
{number}
</li>
);
});
return (
<div>
<ul>
{this.state.fotos? this.state.fotos : 'nothing to display' }
</ul>
<ul id="page-numbers">
{renderPageNumbers}
</ul>
</div>
);
}
}
export default Todo;

React-Bootstrap - Pagination not showing

I'm using the react-bootstrap to paginate the result. It is rendering the div #content, but it is not showing nothing more. It is showing only a empty div with width, height and background color as I configured on the CSS file. I would like to display the pagination showing one house per page. The result of data from JSON is catched successfully. How can I solve the pagination issue? Thanks!
import React, { Component } from 'react'
import axios from 'axios'
import { Pagination } from 'react-bootstrap'
const URL_HOUSES = 'http://localhost:3001/houses';
class Casas extends Component {
constructor(props) {
super(props)
this.state = {
houses: []
}
this.handlePageChange = this.handlePageChange.bind(this)
}
getNumPages(currentPage) {
{ this.handlePageChange }
this.setState({
per_page: this.props.results ,
currentPage: currentPage + 1 ,
previousPage: currentPage - 1
});
}
handlePageChange(page, evt) {
const currentPage = this.state.currentPage || 1;
const numPages = this.getNumPages();
const pageLinks = [];
if (currentPage > 1) {
if (currentPage > 2) {
pageLinks.push(1);
pageLinks.push(' ');
}
pageLinks.push(currentPage - 1);
pageLinks.push(' ');
}
for (let i = 1; i <= numPages; i++) {
const page = i;
pageLinks.push(page);
}
if (currentPage < numPages) {
pageLinks.push(' ');
pageLinks.push(currentPage + 1);
if (currentPage < numPages - 1) {
pageLinks.push(' ');
pageLinks.push(numPages);
}
}
this.setState({ currentPage: currentPage + 1 } );
this.setState({ previousPage: currentPage - 1 } );
}
componentDidMount() {
axios.get(URL_HOUSES)
.then(res => {
this.setState({ houses: res.data })
})
}
render() {
const per_page = "1";
const paginationData = this.state.houses
let numPages = Math.ceil(paginationData.length / per_page);
if (paginationData.length % per_page > 0) {
numPages++;
}
return (
<div>
{this.state.houses.map(item =>
<div>
<h2>{item.name}</h2>
<p>{item.description}</p>
<ul>
{
item.photos.map(photo => <li>{photo}</li>)
}
</ul>
</div>
)}
<Pagination id="content" className="users-pagination pull-right"
bsSize="medium"
first last next prev boundaryLinks items={numPages}
activePage={ this.state.currentPage } onSelect={ this.handlePageChange
} />
</div>
)
}
}
export default Houses;
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Pagination from "react-js-pagination";
require("bootstrap/less/bootstrap.less");
class App extends Component {
constructor(props) {
super(props);
this.state = {
activePage: 1,
itemPerPage: 3,
productList: [],
duplicateProductList: []
};
}
componentDidMount() {
let d = '';
$.get("YOUR API", function (data) {
d = data;
this.setState({
projectList: d,
duplicateProductList: d
});
}.bind(this));
}
handlePageChange(pageNumber) {
this.setState({ activePage: pageNumber });
}
render() {
const { projectList, activePage, itemPerPage } = this.state;
const indexOfLastTodo = activePage * itemPerPage;
const indexOfFirstTodo = indexOfLastTodo - itemPerPage;
const renderedProjects = projectList.slice(indexOfFirstTodo, indexOfLastTodo);
return (
<div>
<div>
YOUR LIST
</div>
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={this.state.itemPerPage}
totalItemsCount={this.state.duplicateProductList.length}
pageRangeDisplayed={5}
onChange={this.handlePageChange.bind(this)}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Can you follow this link https://www.npmjs.com/package/react-js-pagination

Categories

Resources