I have a problem which requires me to store the texted of a referenced element in an array.
Now, I first want to display the text for each element(paragraph element with "ebookName" class) in the console, before storing it in the array.
But I have been having problems... Whenever I click an element, the console just logs the previous elements text always. I want for each paragraph element to log that specific elements text, not the previous one
Link to JS code:
import React from 'react'
import "./Styles/Ebook.css"
import { useRef } from 'react';
function Ebook() {
const bookName = useRef();
let ebookData = JSON.parse(sessionStorage.getItem("ebook"));
/*function that displays the specific text of a specific element onto the console*/
const elementLogFunction = () =>{
console.log(bookName.current)
}
return (
<section id="musicRender">
{ebookData.results.map((ebook, i)=>{
return (
<div key={i} className='ebookContentContainer'>
<div className="ebookPicture">
<img src={ebook.artworkUrl100} alt={ebook.trackName} />
</div>
<div className="ebook-description">
<p className="ebookAuthor">Author: {ebook.artistName}</p>
<p ref={bookName} className='ebookAName'>Book Name: {ebook.trackName}</p>
<p className="price">Price: R{(ebook.price * 15.36).toFixed(0)}</p>
<button onClick={elementLogFunction} className="favourites-btn">Add To Favourites</button>
</div>
</div>)
})}
</section>
)
}
export default Ebook
According to your code, ref is only referred to the same data, and the new one will override the old one. In your case, the last book data will be kept.
If you want to have individual book data separately, you can pass a param to elementLogFunction.
You also shouldn't read sessionStorage every rendering. This behavior causes a performance issue due to getting data multiple times. You can use useEffect to read data only once after the first rendering.
function Ebook() {
const [ebookData, setEbookData] = React.useState([]);
//only add data for the first rendering
useEffect(() => {
setEbookData(JSON.parse(sessionStorage.getItem("ebook")));
}, []);
/*function that displays the specific text of a specific element onto the console*/
const elementLogFunction = (ebook) =>{
console.log(ebook.trackName)
}
return (
<section id="musicRender">
{ebookData.results.map((ebook, i)=>{
return (
<div key={i} className='ebookContentContainer'>
<div className="ebookPicture">
<img src={ebook.artworkUrl100} alt={ebook.trackName} />
</div>
<div className="ebook-description">
<p className="ebookAuthor">Author: {ebook.artistName}</p>
<p ref={bookName} className='ebookAName'>Book Name: {ebook.trackName}</p>
<p className="price">Price: R{(ebook.price * 15.36).toFixed(0)}</p>
<button onClick={() => elementLogFunction(ebook)} className="favourites-btn">Add To Favourites</button>
</div>
</div>)
})}
</section>
)
}
export default Ebook
I'm building an app using the Google Books API and I appear to be passing a unique key to each child in the list, but the error won't go away. I must be doing something wrong but I'm not sure what.
const BookList = (props) => {
//map over all of the book items to create a new card for each one in the list
const books = props.books.data.items.map((book) => {
console.log(book.id);
return (
<div className="col col-lg-4 grid-wrapper">
<BookCard
key={book.id}
image={book.volumeInfo.imageLinks.thumbnail}
title={book.volumeInfo.title}
author={book.volumeInfo.authors[0]}
description={book.volumeInfo.description}
previewLink={book.volumeInfo.previewLink}
buyLink={book.saleInfo.buyLink}
/>
</div>
);
});
return <div>{books}</div>;
};
Notice that after the return in const books I have a console.log(book.id), which will display all 10 unique id keys in the console. But when I try to pass it to the child of this component using key={book.id}, I get this error.
The key needs to go on the outermost returned element. In your specific case, that means changing this:
<div className="col col-lg-4 grid-wrapper">
<BookCard
key={book.id}
to this:
<div className="col col-lg-4 grid-wrapper" key={book.id}>
<BookCard
I was using React fragments in my map() call in their simple syntax form, and was running into the same warnings with the code below:
<>
<h3>{employee.department}</h3>
<TableRow
key={employee.id}
cellValues={["Name", "Title"]} />
<TableRow
key={employee.id}
cellValues={[employee.name, employee.title]}
/>
</>
Building off the accepted answer, I realized I needed the outermost element to have the ID. I learned of an alternate syntax for React fragments that allows one to put an ID on it. The resulting code below caused the warnings to go away:
<React.Fragment key={employee.id}>
<h3>{employee.department}</h3>
<TableRow
cellValues={["Name", "Title"]} />
<TableRow
cellValues={[employee.name, employee.title]}
/>
</React.Fragment>
I have created a component and it's running well in local server. But I am getting below warning
Warning: Each child in a list should have a unique "key" prop.
Getting this warning means we need to fix the key index props? as given here.
below is some snippets of my component code..
render() {
return (
<div>
<Container>
<Row>
<Col className="col-12">
{this.state.client.map((val,index)=>{
if(index == this.state.colaborators.length -1)
return <a href={"/users/"+val}>{val}</a>
return <a href={"/users/"+val}>{val} ,</a>
})}
</Col>
</Row>
</Container>
</div>
</div>
</div >
);
}
}
export default App;
I checked some solution from here
As I told my code is working well. Can we use some fake key props? for example
key={fake index}
And we are using will this affect in my working code?
If this.state.client ever changes, don't just use the index (which is sadly common); see this article for why and its demo of what can go wrong. You can only do that with a list that never changes, or only grows/shrinks (and not at the same time), not with one where the order changes (you insert at the beginning, or sort, or...) More in the docs.
I'm guessing val will be unique in the list, so use that as the key:
{this.state.client.map((val, index) => {
const href = "/users/" + val;
const display = index == this.state.colaborators.length - 1 ? val : `${val} ,`;
return <a key={val} href={href} >{display}</a>;
})}
If your lists order is not going to change, simply use:
return <a key={index} href={"/users/"+val}>{val}</a>
return <a key={index} href={"/users/"+val}>{val} ,</a>
It will not affect your code and it will remove the warning.
I have a list of objects photos, from a json data file, that I would like to organize into 3 different <div> columns, but I dont know how to achieve that, here is my broken non-optimized code:
<div className="container">
<div ref={leftColRef} className="left-col" />
<div ref={centreColRef} className="centre-col" />
<div ref={rightColRef} className="right-col" />
{Object.keys(photos).forEach((n, i) => {
const id = photos[n].id;
const thumb = photos[n].thumbnailUrl;
const title = photos[n].title;
const element = (
<Thumbnail id={id} title={title} thumb={thumb} />
);
if (i % 3 === 0) {
leftColRef.current.append(element);
} else if (i % 3 === 1) {
centreColRef.current.append(element);
} else {
rightColRef.current.append(element);
}
// this line works, it idsplays the data but is commented as the data needs to go inside its respective columns
// return <Thumbnail key={id} title={title} thumb={thumb} />;
})}
</div>
The idea is to insert some elements into the left-column when i%3 = 0 and others in the centre-column when i%3 = 1 and so on ...
And a link to my codesandbox
Any help/advise will be much appreciated.
Easiest is probably to prepare the data outside the render function and to render the column one by one.
You should not manipulate the DOM like it's done in jQuery using JSX
Example:
const Component = (props) => {
const filterPhotos = (column) => {
return props.photos.filter((photo,index)=> index%3==column);
}
return <>
<MyColumn photos={filterPhotos(0)}/>
<MyColumn photos={filterPhotos(1)}/>
<MyColumn photos={filterPhotos(2)}/>
</>;
}
First, using ref on div to inject stuff on it is wrong. It's the opposite of how react works.
Like charlies said, I would split the photos in 3 different arrays before the render. Then, you'll be able to do something like this :
<div ref={leftColRef} className="left-col" />
{ photosLeft.map(photo => <Thumbnail key={photo.id} {...photo} />)
</div>
when preparing your data, try to use the same object properties and component props name so you can spread it easily ( {...photo} ).
Note: Also, when rendering an array in react, each child must have a unique key props. It will help react to render on that part of dom if your data change.
I am working in a Spring application that uses react. Currently I have a json that contains several users based on certain criteria. The number of users can vary, but I would like to create several buttons for each user returned that links to the users profile. the url is just '/profile/username'
format of json
[{"user":{"principal":"cat#sitter.com","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"cat#sitter.com","zipcode":"98077","firstname":"cat","password":"abc123","sitterFlag":"true","ownerFlag":"false","lastname":"sitter","username":"catsitter","preferredPet":"Cat"},"momento":"cat#sitter.com"},"password":"$2a$10$ltnL.mFqo7hatj69Ls76xeegjhEX0D4At9m1rlBHbQtDrV8MdSeAS","momento":"cat#sitter.com"},{"user":{"principal":"test#pets.com","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"test#pets.com","zipcode":"98077","firstname":"test","password":"abc123","sitterFlag":"false","ownerFlag":"false","lastname":"pets","username":"testpets"},"momento":"test#pets.com"},"password":"$2a$10$wDhS6Mb8syhC0YIqgVG2qu8J6lA.1T.UprMYwAX6O7Xb3YMhgX3bO","momento":"test#pets.com"},{"user":{"principal":"test#sitter.com","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"test#sitter.com","zipCode":"98077","firstname":"test","password":"abc123","lastname":"sitter","username":"testsitter"},"momento":"test#sitter.com"},"password":"$2a$10$DuIeWFSzhtAjX3lr8xBNiu2kV9kAJ/PQ6pB/EzkB7FkGWfRbwxkzy","momento":"test#sitter.com"},{"user":{"principal":"sit#sitter.com","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"sit#sitter.com","zipCode":"98077","firstname":"sit","password":"abc123","lastname":"sitter","username":"imasitter"},"momento":"sit#sitter.com"},"password":"$2a$10$2NKOQkGZO/jUer3UjNGzdugUhkMV1pJ1eT8NQjSPRto9/cRdm56sO","momento":"sit#sitter.com"},{"user":{"principal":"a#sitter.com","schedule":null,"appointments":null,"roles":["ROLE_USER"],"attributes":{"principal":"a#sitter.com","zipCode":"98077","firstname":"a","password":"abc123","lastname":"sitter","username":"asitter"},"momento":"a#sitter.com"},"password":"$2a$10$8x1uVqR28x5rwNrydieSyu1ILifBJ5n0dUsZI5tJ6MoUWMqXxrmeq","momento":"a#sitter.com"}]
I currently have it working if I hard code for each user:
<div className="container padded">
<div className="row">
<div className="col-6 offset-md-3">
<h2>Suggested Sitters</h2>
<button onClick={() => this.suggestSitter(this.props.user.principal)}>Click</button>
<hr/>
<div>
Sitters:
</div>
<Link to={this.setProfile(this.state.sitter ? this.state.sitter[1].user.attributes.username: ' ')} >
<button type="button">{this.state.sitter ? this.state.sitter[1].user.attributes.username: ' '}</button>
</Link>
</div>
</div>
</div>
the setProfile works like this:
setProfile(theUser) {
return '/profile/' + theUser;
}
Clicking a button will redirect to that user's profile page.
So basically, instead of hardcoding n buttons, I would like to dynamically create n buttons and each will link to '/profile/username/ for each user returned.
suggestSitter function:
suggestSitter(user){
var _this = this;
console.log('user', user);
axios.get('/api/user/suggest_sitter', { params: { principal: user } })
.then(function(response) {
console.log('Response: ' + JSON.stringify(response));
_this.setState({
sitter: response
});
})
.catch(function (e) {
console.log('Error: ' + e);
});
}
You can map the data to an array of Link (provide an unique key for it too):
{this.state.sitter.map((e) => (
<Link key={e.someUniqueProperty} to={this.setProfile(e.user.attributes.username)}>
<button type="button">{e.user.attributes.username}</button>
</Link>
))}
Suppose your data is:
const data = [
{user: {...}, attribute: {...}},
{user: {...}, attribute: {...}},
...
]
Now, you can follow these steps:
Create a stateless/stateful component(depending on your use case): UserButton or any other meaningful name:
const UserButton = () => (
<div className="container padded">
<div className="row">
<div className="col-6 offset-md-3">
/*...Add your remaining JSX....*/
</div>
</div>
</div>
)
Now in your parent component(from where you are actually rendering the data), you can do the following:
renderUserButtons = () => {
return data.map((userData) => (
<UserButton key="Some-unique-id-can-be-anything" PASS_YOUR_PROPS_HERE/>
))
}
render() {
return (
<div>
...
{this.renderUserButtons()}
...
</div>
);
}
Obviously, you don't need multiple components for this, but splitting it into smaller components looks good, easier to maintain and easier to test. Again it's my personal preference. You can use the convention whatever is best for you.
To create any UI component from some array, you can always use map function like below.
Array of JSON Object
let users = [{"name":"ABC"},{"name":"DEF"},{"name":"GHI"}];
Map Function
let userList = users.map((user,index)=>{return (<div>{index} - {user.name}<div>)})
this will give you following output:
0 - ABC
1 - DEF
2 - GHI
in map function user is the reference to one by one users from the array. Index is the key for each value from array (ex. 0,1,2....).
We are returning a JSX object from the return statement.
You can now use userList variable in render's return. Like below..
render(){ let userList = "...."; return(<div>{userList}</div>
I hope this would help.