react js match rows with similar data - javascript

I am facing an issue in react js. I want to match row data according to column values.
my react component:
<div className="row">
{this.state.staff.map((data, i) => (
<div className="full-block">
<p key={i}>
{data.full_name}
</p>
</div>
)
)}
</div>
My output
Expected output
working demo
https://codesandbox.io/s/elegant-sara-3ebcq?file=/src/App.js
what should i do? what i change in my code?

Related

How to use dynamic image path in next js

I am new in reactjs and i am working with nextjs,I am fetching image from datbase via api, Right now i am getting image name with full path ( url.com/imagename) but i want to know how can we use dynamic path, in other words if i have only "image name" (not full path) so how can i append "image path" for display image using next js? I tried with following code
{this.state.books.map((post, index) => {
return (
<div className="col-md-4"
<div className="bookimg">
<img src={post.image} />
</div>
</div>
)
})}
Let's say that post.image give you the image name only with mimi type.
{this.state.books.map((post, index) => {
return (
<div className="col-md-4"
<div className="bookimg">
<img src={`myurl.com/image/${post.image}`} />
</div>
</div>
)
})}

Passing of Props in ReactJS

Following is my JSX code in a React component which is working fine and currently in use, but in most of React blog posts they are also de structuring an object. My query is - do we have any extra benefit of modifying the code to Version 2 or this is just fine.
First Version (currently in use) -
const CartItems = ({ items }) => items.length ? items.map((x, i) => (
<div key={x.id} className={`cart-item-${i}`}>
<div className="card ">
<div className="cart-item-img">
<img src={x.url} alt={x.altText} className="img" />
</div>
<div className="cart-item-desc">
<h3 className="title">{x.title}</h3>
<p className="text">{x.shortDesc}</p>
</div>
<div className="cart-item-action">
<button className="add">+</button>
<button className="subtract">-</button>
<button className="remove">X</button>
</div>
</div>
</div>)) : []
2nd Version -
const CartItems = ({ items }) => items.length ? items.map((x, i) => {
const {
id,
url,
altText,
title,
shortDesc
} = x;
return (
<div key={id} className={`cart-item-${i}`}>
<div className="card ">
<div className="cart-item-img">
<img src={url} alt={altText} className="img" />
</div>
<div className="cart-item-desc">
<h3 className="title">{title}</h3>
<p className="text">{shortDesc}</p>
</div>
<div className="cart-item-action">
<button className="add">+</button>
<button className="subtract">-</button>
<button className="remove">X</button>
</div>
</div>
</div>)
}) : []
The benefits are mostly aesthetic and subjective, so if you prefer the first one, more power to you and nothing that says you need to change it.
My personal view on the two snippets you posted: I tend to avoid direct returns from arrow functions because I'll oftentimes need to add a log or something else and having to convert back and forth eventually wears on you. This has little to do with the destructuring though, other than destructuring forces you to have a function body and explicit return.

React JS render list data in separate row

I am facing an issue in React Js. I want to show names data in each separate row.
const names = ['James', 'John', 'Paul', 'Ringo'[![\]][1]][1];
My Code:
return (
<div class="col-lg-8 bar-name">
<div>
{names.map(filteredName => (
<li>
{filteredName}
</li>
))}
</div>
</div>)
How can i use in div element ? What should i do?
can anyone help me?
You need to add elements to want to be displayed alongside in the List tag.
Example:
return (
<div class="col-lg-8 bar-name">
<div>
{names.map(filteredName => (
<li>
{filteredName}
<div>
Ryan
</div>
<div>
Eric
</div>
</li>
))}
</div>
)

How to properly search in a list in ReactJS

I am trying to set a simple search operation in a user interface as shown below:
I have a total of 70 react-strap cards and each card contain a vessel with name, type and an image. I would like to search the name of the vessel and have the card related to that vessel to pop-up. All my images are currently contained inside the external database Contentful. Below the fields of interests:
The problem is that I don't know how to write a search function that locate a specific value of a list.
Below the code:
SideBar.js
import React from 'react';
import Client from '../Contentful';
import SearchVessel from '../components/SearchVessel';
class Sidebar extends React.Component {
state = {
ships: [],
};
async componentDidMount() {
let response = await Client.getEntries({
content_type: 'cards'
});
const ships = response.items.map((item) => {
const {
name,
slug,
type
} = item.fields;
return {
name,
slug,
type
};
});
this.setState({
ships
});
}
getFilteredShips = () => {
if (!this.props.activeShip) {
return this.state.ships;
}
let targetShip = this.state.ships.filter(
(ship) => this.props.activeShip.name === ship.name
);
let otherShipsArray = this.state.ships.filter((ship) => this.props.activeShip.name !== ship.name);
return targetShip.concat(otherShipsArray);
};
render() {
return (
<div className="map-sidebar">
{this.props.activeShipTypes}
<SearchVessel />
<pre>
{this.getFilteredShips().map((ship) => {
console.log(ship);
return (
<Card className="mb-2">
<CardImg />
<CardBody>
<div className="row">
<img
className="image-sizing-primary"
src={ship.companylogo.fields.file.url}
alt="shipImage"
/>
</div>
<div>
<img
className="image-sizing-secondary"
src={ship.images.fields.file.url}
alt="shipImage"
/>
</div>
<CardTitle>
<h3 className="thick">{ship.name}</h3>
</CardTitle>
<CardSubtitle>{ship.type}</CardSubtitle>
<CardText>
<br />
<h6>Project Details</h6>
<p>For a description of the project view the specification included</p>
</CardText>
<Row style={{ marginTop: '20px' }}>
<div className="buttoncontainer">
<div className="btn btn-cards">
<a
className="buttonLink"
download
href={ship.projectnotes.fields.file.url}
>
Project Notes
</a>
</div>
<div className="btn btn-cards">
<a className="buttonLink" href={ship.abstract.fields.file.url}>
Abstract
</a>
</div>
</div>
</Row>
</CardBody>
</Card>
);
})}
</pre>
</div>
);
}
}
export default Sidebar;
VesselSearch.js
import React, { Component } from 'react';
export default class SearchVessel extends Component {
render() {
const { value, handleSubmit, handleChange } = this.props;
return (
<React.Fragment>
<div className="container">
<div className="row">
<div className="col-10 mx-auto col-md-8 mt-5 text-center">
<h4 className="text-slanted text-capitalize">Search for Vessel</h4>
<form className="mt-4" onSubmit={handleSubmit}>
<label htmlFor="search" className="text-capitalize">
type vessel separated by comma
</label>
<div className="input-group">
<input
type="text"
name="search"
placeholder="Type name of vessel here"
className="form-control"
value={value}
onChange={handleChange}
/>
<div className="input-group-append">
<button type="submit" className="input-group-text bg-primary text-white">
<i className="fas fa-search" />
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</React.Fragment>
);
}
}
What I have done so far:
1) I tried different combination with the filter function and I think I am close. The problem is that when I operate the search nothing happens and in order to find the card of the vessel I want, I have to scroll down until I find it.
I am running out of ideas and if you see something I didn't catch point me in the right direction for solving this issue.
You're close! I would add a field to your state called 'searchText' and then create a method to filter based on that searchText state item.
getFilteredShips = () => this.state.ships.filter(s => s.name.includes(this.state.searchText)
Then just map over those values to render the cards that match the search text. The cards will update each time the searchText value updates.
this.getFilteredShips().map(ship => ..........
React is famous for re-usable component. You will have all the data of these vessels in an array. You will loop through the array and render the items with card component.And when you search for the specific card you want that vessel to pop out on top.
There are two ways to do it:
You have to run through the array, find the index of that vessel and do whatever it takes to manipulate your array and to make that item at top and re-render your list.
Alternatively render one more component on top of your vessel list as user clicks the search button. You just have to find the item index and render it. This way you don't have to deal with array manipulation. It doesn't matter if you have 80 or 1000 cards.
Please checkout official documentation for array methods, for array slicing and splice.
Hope this is what you are looking for. If you need further help, comment please.

ReactJS - How to setSate in a map function

I got an object with another object inside and I need to render the DOM like this:
Event
Tickets 1
Lot 1
Name
Lot 2
Name
Lot 3
Name
Ticket 2
Lot 1
Name
Lot 2
Name
{ this.state.dates.map((date, i) =>
<span className="event-date" key={i}>
{ date.date }
</span>
this.setState({tickets: date.tickets}) //Here, I need to update an object to map in another place
)}
./src/pages/Event/Event.js
Syntax error: D:/YEAPPS/marketplace/pwa/src/pages/Event/Event.js: Unexpected token, expected , (54:32)
Click to see the object
Do not call setState from within a render function, it will cause unnecessary rerenders, i.e. do not update the state with your tickets here
Set up your state within the component using other lifecycle hooks, e.g. componentDidMount, then simply map over your this.state.tickets.map(), or as you are already doing, this.state.dates.map()
I was able to solve like this:
{
this.state.tickets.map((ticket, i) => (
<div key={i}>
<div className="row">
<div className="col">
<h3 className="ticket-name">{ ticket.name }</h3>
</div>
</div>
{ticket.lot.map((lot, j) =>
<div className="row" key={i}>
<div className="col-8">
<h5 className="lot-name">{ lot.name }</h5>
<h6 className="lot-price">
R$ { lot.price.replace('.', ',') } <br />
<small>(R$ { lot.price.replace('.', ',') } + R$ { lot.price_tax.replace('.', ',') })</small>
</h6>
</div>
<div className="col-4">
<ChooseQuantity />
</div>
</div>
)}
<hr />
</div>
)
)
}

Categories

Resources