I have these three imports and I want to use them accordingly.
import avatar1 from "../../../../assets/images/user/avatar-1.jpg";
import avatar2 from "../../../../assets/images/user/avatar-2.jpg";
import avatar3 from "../../../../assets/images/user/avatar-3.jpg";
And I have this map function and I want to show these three images as map function executes.
So I wrote this:
{this.state.empData.map((emp, index) => (
<tr className="unread" key={emp.id}>
<td>
{index + 1 <= 3 ? (
<img
className="rounded-circle"
style={{ width: "40px" }}
src={`avatar` + { index }}
alt="activity-user"
/>
) : (
(index = 0) // i want to reset the index, so it would start from 0 again
)}
</td>
</tr>
))}
So what i want is, if I have 10 iterations through that map function, and I have 3 avatars, I want to show each 10 image so each 3 avatars are repeated from avatar1 to avatar3 as long as map iterates.
Above method I tried, doesn't work as images a re not showing.
Can you help me?
Write a selector function and use the modulus
You can use modulus to repeat a series of numbers. it always returns the remainder of the division. e.g. 3 % 3 === 0 6 % 3 === 0 1 % 3 === 1
const selectImage = (index) {
if (index % 3 === 0) {
return avatar1; // or return "../../../../assets/images/user/avatar-1.jpg"
}
if (index % 3 === 1) {
return avatar2; // or return "../../../../assets/images/user/avatar-2.jpg"
}
if (index % 3 === 2) {
return avatar3; // or return "../../../../assets/images/user/avatar-3.jpg"
}
}
and then in your component
<img
className="rounded-circle"
style={{ width: "40px" }}
src={selectImage(index)}
alt="activity-user"
/>
Related
Code-:
const ClickHighlight = (event, id) => {
if (event.ctrlKey) {
// add to highlighted
setHighlightedRows((current) => {
if (current.includes(id)) {
// row is already highlighted. Unhighlight but keep the others
return current.filter((entry) => entry !== id);
} else {
// add row to the current list of highlighted ones
console.log("nn", ...current, id);
return [...current, id];
}
});
} else if (event.shiftKey) {
event.preventDefault();
previousRow = id;
// add to highlighted
setHighlightedRows((current) => {
if (current.includes(id)) {
// row is already highlighted. Unhighlight but keep the others
// console.log("shift", current);
return current.filter((entry) => entry !== id);
}
else {
// add row to the current list of highlighted ones
console.log("else", id);
console.log("elsecurrent", current);
return [...current, id];
}
});
}
else {
// highlight clicked row and de-highlight others
setHighlightedRows([id]);
}
}
table:-
<tr key={comment.idx} tabIndex={comment.idx} className="border_bottom" onKeyDown={(e) => handleKeyDown(e, comment.idx)} onLoad={() => active(comment.idx)}
ref={comment.idx === 0 ? myRef : null}
onMouseDown={(e) => ClickHighlight(e, comment.idx)}
style={isHighlighted ? { backgroundColor: '#254368' } : {}}>
<td style={{ color: "white", width: "200px" }}>
<img src={`data:image/jpeg;base64,${base64}`} alt="Clip Thumbnail" width="50%" />
</td>
<td style={{ color: "white", width: "440px" }}>{comment.ClipName}</td>
please help I want when users click the shift + mouse click than 1 row and 2 last rows. All rows selected btw them with the index number number
please help...
If user press shift + left click from 1 row to 2 last row then all row btw one and 2 last became selected/focused right now only ctrl + mouse click is working so how can i do the shift + click in react js
ReactJS - I implement Binary Search Function, it works only first time but after I change the value in the input box, it always return -1 even it has the value in the Array.
Please see the following code:
import React, { useState } from 'react'
import { Container } from 'react-bootstrap'
const binarysearch = () => {
const [ insertValue, setInsertValue ] = useState(0)
var exarr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
// Binary Search
const binarySearch = (arr, val) => {
let start = 0, end = arr.length - 1
while (start <= end) {
let mid = Math.floor((start + end)/2)
console.log(mid)
if (arr[mid] === val) {
return mid
}
if (val < arr[mid]) {
end = mid - 1
} else {
start = mid + 1
}
}
return -1
}
// End Binary Search
return (
<div>
<br />
<hr />
<Container>
<h1>Binary Search</h1>
<h4>Array = {JSON.stringify(exarr)}</h4>
<h4>Search <input type="number" onChange={e => setInsertValue(e.target.value)} /></h4>
<h3>Search {insertValue}, Result in location: {binarySearch(exarr,insertValue)}</h3>
</Container>
<hr />
</div>
)
}
export default binarysearch
First Time Load
After Change Input (Search 10 it should return 10 but -1)
The problem is the fact that e.target.value is always a string, even when the input type attribute is set to "number".
So, when you do arr[mid] === val it will be always false, since this is comparing a number to a string.
You can see this behaviour here.
To fix this, do onChange={e => setInsertValue(Number(e.target.value))}.
Or, alternatively, you can use the non strict equality comparison, which is not really recommended, by replacing the === operator by just ==.
Thank you very much #Mario Vernari
I update the below line to change from string to number, it works properly.
(Insert '+' to insertValue)
From
<h3>Search {insertValue}, Result in location: {binarySearch(exarr,insertValue)}</h3>
To
<h3>Search {insertValue}, Result in location: {binarySearch(exarr, +insertValue)}</h3>
So I need to make a table where each product corresponds to a cell; however, there's something with the JSX that prevents me from returning jsx when I don't close the tags in the returned JSX. I am not sure if there are alternate methods, but it seems that I am in a kind of bind, because the error message doesn't make sense and I get things like unexpected token.
Tried to return the JSX with map inside the callback, but it seems I can't do exactly what I want.
{props.products.slice(0, 50).map((element, i) => {
console.log(element.name);
if (i % 5 == 0) {
return (
<TableRow>
<TableRowColumn>{element.name}</TableRowColumn>
)
} else if (i % 5 == 4) {
return (
<TableRowColumn>{element.name}</TableRowColumn>
</TableRow>
)
} else {
return (
<TableRowColumn>{element.name}</TableRowColumn>
)
}
})}
I expect each row to have 5 columns, and each cell containing a product and the table containing 50 elements. Basically, I want to close the row after 5 column.
I would like to have something like a 5 by 5 table in the end or 5 by 10 to be exact.
You can check some examples on material-ui site (https://material-ui.com/demos/tables/)
If you know which elements are headers names you can use for-loop over products to create columns name e.g.
<TableRow>
{props.products.map((product, index) => {
if (index % 5 === 0) {
return <TableCell>{product.name}</TableCell>;
}
}
</TableRow>
JSX is not HTML and you cannot brake up tag pairs.
Proper solution should be like this
function chunker(array, length) {
// select proper implementation on the link below
return []
}
{chunker(props.products.slice(0, 50)), 5).map((chunk) => {
if (chunk.length !== 5) {
console.warn('not full chunk', chunk)
}
return (
<TableRow>
{chunk.map((element, i) => {
console.log(element.name);
return (
<TableRowColumn>{element.name}</TableRowColumn>
)
})}
</TableRow>
)
})}
Select chunk implementation here Split array into chunks
I'm trying to wrap every two posts inside a container div. Below is what I tried, but unfortunately I get an error.
This is what I tried:
I have a variable called postIndex. While the posts are being iterated over with posts.map(({ node }) => {...}, I have a conditional if/else check to see if postIndex is odd or even with if (postIndex % 2 == 0) (check if postIndex is even) and if (postIndex % 2 == 1) (check if postIndex is odd).
If postIndex is even I render out only the opening <div> tag that is the container for the two posts. If postIndex is odd, then I render out only the closing </div> tag.
I get an error with this implementation, though. What is the right way to go about doing something like this?
Example of what I tried:
let postIndex = 0
return (
<Layout>
{posts.map(({ node }) => {
if (postIndex % 2 == 0) {
postIndex++
return (
<div>
<p>test</p>
)
} else if(postIndex % 2 == 1) {
postIndex++
return (
<p>Test</p>
</div>
)
}
})
}
</Layout>
)
An opening tag without a closing tag is invalid JSX. You can probably do something like this below though. Also, you have access to the index of the array in a map, so you don't need to create a new variable.
return (
<Layout>
{posts.map(({ node }, index) => {
if (index % 2 === 0) {
return (
<div key={index}>
<p>{node}</p>
{posts[index + 1] && <p>{posts[index + 1].node}</p>}
</div>
)
}
})
}
</Layout>
)
I'm trying to render a component that takes data from a local API and it's been set it into multiple states, at the moment I'm mapping through one state and I need to use some data from another state. How can I access this data and map through it once?
In prodsLink={'https://www.sodimac.cl/sodimac-homy/product/' + skuData.productId + '/'}
I need to render something like this:
https://www.sodimac.cl/sodimac-homy/product/productID/productLocation
but if I do this:
prodsLink={'https://www.sodimac.cl/sodimac-homy/product/' + skuData.productId + '/' + this.state.ids.map(skuMarca => skuMarca.marca)}
It will render something like this:
https://www.sodimac.cl/sodimac-homy/product/productID/productLocation01,productLocation02,productLocation03,productLocation04
UPDATE:
This is the output I'm looking for (once per loop not all of them in one array):
BUTTON 01
BUTTON 02
BUTTON 03
BUTTON 04
I know is confusing so here is my code.
render() {
return (
this.getWebServiceResponse(this.state.ids.map(e => e.sku).join('-'), 96),
this.state.active == true &&
<div className="row" style={{ width: '89%', margin: '0 auto' }}>
<div className="blockCatPriceSlide">
{this.state.products.map(skuData =>
window.innerWidth > 440 && skuData.status === 'OK' ?
<ContenidoUno
prodsName={skuData.name.substr(0, 30) + '...'}
prodsId={skuData.productId}
prodsStatus={skuData.status}
prodsPublished={skuData.published}
prodsNormal={skuData.NORMAL.toLocaleString().replace(',', '.')}
prodsCMR={skuData.CMR}
prodsCombo={skuData.combo}
prodsAhorro={skuData.savings}
prodsStock={skuData.stockLevel}
prodsAntes={skuData.NORMAL + skuData.savings > skuData.NORMAL ? <small> Antes: $ {skuData.NORMAL + skuData.savings} </small> : ''.toLocaleString().replace(',', '.')}
prodsLink={'https://www.sodimac.cl/sodimac-homy/product/' + skuData.productId + '/'}
prodsImg={'https://picsum.photos/g/570/250'}
prodsIcon={(skuData.combo === true &&
<img src='https://via.placeholder.com/100x50/f41435/ffffff?text=combo' className="iconic" alt="producto" />) ||
(skuData.CMR !== undefined && <img src='https://via.placeholder.com/100x50/f41435/ffffff?text=CMR' className="iconic" alt="producto" />)}
catName={skuData.webCategoryName}
/> :
<ContenidoUno
prodsName={'Producto sin informaciĆ³n...'}
prodsId=''
prodsStatus=''
prodsPublished=''
prodsNormal=''
prodsCMR=''
prodsCombo=''
prodsAhorro=''
prodsStock=''
prodsAntes=''
prodsLink=''
prodsImg={'https://picsum.photos/g/570/250'}
prodsIcon=''
catName=''
/>
)
}
</div>
</div>
)
}
}
Array.prototype.map returns a new array, so in this situation you're just returning array of [marca?, marca?, ...], so instead of returning, marca? from map you should returning whole link like so:
prodsLink={ this.state.ids.map(({ marca }) =>
`https://www.sodimac.cl/sodimac-homy/product/${skuData.productId}/${marca}`
)}
this will generate link array:
[
https://www.sodimac.cl/sodimac-homy/product/${skuData.productId}/${marca},
https://www.sodimac.cl/sodimac-homy/product/${skuData.productId}/${marca},
https://www.sodimac.cl/sodimac-homy/product/${skuData.productId}/${marca},
...
]