i'm currently learning ReactJS, and im facing an issue while tryng to hide/show a div! The following code is working, but when i'm clicking the button "Learn More" it hide every description on every card, but i would like to show/hide the description only where i clicked it.
import Axios from 'axios';
import React, { useEffect, useState } from 'react';
import JobApplicationList from './JobApplicationList';
import Card from "react-bootstrap/Card";
import ScriptTag from 'react-script-tag';
export default class Home extends React.Component{
constructor(){
super()
this.state={
showMe:true,
advLists: []
}
}
operation(){
this.setState({
showMe:!this.state.showMe
})
}
componentDidMount() {
Axios.get(`http://localhost:3001/get/adv`)
.then(res => {
const advLists = res.data;
this.setState({ advLists });
})
}
render(){
return (
<div className="main-page">
<div className="adv_container">
{this.state.advLists.map((val, key) => {
return (
<div className="card_">
<Card style={{ width: "100%" }}>
<Card.Body>
<Card.Title>{val.compName}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">
{val.city} | {val.compWebsite}
</Card.Subtitle>
<Card.Subtitle className="mb-2 text-muted">
{val.salaire} €
</Card.Subtitle>
{ this.state.showMe?
<div className="description">
<Card.Text>{val.description}</Card.Text>
</div>
:null
}
<Card.Link onClick={()=> this.operation()} id="toto" href="#">Learn more</Card.Link>
<Card.Link href="#">Apply</Card.Link>
</Card.Body>
</Card>
</div>
);
})}
</div>
</div>
)
}
}
I kinda know what's going wrong, when i'm pressing the button i give the showMe state to every card, but i dont know how to fix it!
Thanks in advance for the help.
Make the initial showMe state null and convert operation to take an index to toggle. If the index is already saved in state then set back to null.
operation(index) {
this.setState({
showMe: this.state.showMe === index ? null : index,
})
}
Use the mapped index to pass to the handler and check this index against the showMe state to display the card.
{this.state.advLists.map((val, key) => {
return (
<div className="card_">
<Card style={{ width: "100%" }}>
<Card.Body>
<Card.Title>{val.compName}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">
{val.city} | {val.compWebsite}
</Card.Subtitle>
<Card.Subtitle className="mb-2 text-muted">
{val.salaire} €
</Card.Subtitle>
{this.state.showMe === key && ( // <-- check if index/key matches
<div className="description">
<Card.Text>{val.description}</Card.Text>
</div>
)}
<Card.Link
onClick={() => this.operation(key)} // <-- pass key/index to toggle
id="toto" href="#"
>
Learn more
</Card.Link>
<Card.Link href="#">Apply</Card.Link>
</Card.Body>
</Card>
</div>
);
})}
I can give you the code pattern on how to toggle individual items using a React class component.
class MyComponent extends React.Component {
state = { items: [] }; // initial state
componentDidMount() {
// fetched data
this.setState({ items: [{ title: "one" }, { title: "two" }] });
}
toggleItem = (index) => {
let items = this.state.items;
items[index].hidden = !items[index].hidden; // mutating
this.setState({ items }); // new object triggers re-render
};
render() {
return (
<ul>
{this.state.items.map((item, index) => {
return (
<li key={index}> {/* remember to use a key */}
<button onClick={() => this.toggleItem(index)}>toggle</button>
{!item.hidden && item.title}
</li>
);
})}
</ul>
);
}
}
Related
its a long explaition it will be easier if you see screenshots first!
i'm trying to make a website, which inside 3 divs, with 3 different backgrounds. under those 3 divs there are 3 rows of buttons with different colors
you click on a color, it changes the background of one of the main divs. it will be more clear with the image/codesandbox i give here
each click you make changes "this.state.color1" or "color2" to the color you clicked on.
what i wanna do is add a "saved selection page", which you can see color combinations you saved by clicking another buttons called "save".
each click on this save button should return the 3 current colors, send them over to "Saved" page, and they should stay there and never change.
and if you click the save button again, it keeps the previous selections, and add the new one under the previous one.
kinda the same way we click on "add to cart" on websites.
i tried over a week to figure it out by many different ways, like putting a new state called "savedColors" and stuff like that but i didnt figure it out.
here it is on codesandbox
main page:
import React from "react";
import "./main.style.css";
import Buttons1 from "../buttons/buttons1-component";
import Buttons2 from "../buttons/buttons2-component";
import Buttons3 from "../buttons/buttons3-component";
import Saved from "../saved/saved.component";
class Main extends React.Component {
constructor(props) {
super(props);
this.changeColor1 = this.changeColor1.bind(this);
this.changeColor2 = this.changeColor2.bind(this);
this.changeColor3 = this.changeColor3.bind(this);
this.changeToSavedPage = this.changeToSavedPage.bind(this);
this.goToMainPage = this.goToMainPage.bind(this);
this.saveScheme = this.saveScheme.bind(this);
this.state = {
color1: "#fff285",
color2: "#38306b",
color3: "#c4cc90",
page: "main"
};
}
changeToSavedPage() {
this.setState({ page: "saved" });
}
goToMainPage() {
this.setState({ page: "main" });
}
changeColor1(id) {
this.setState({
color1: id
});
}
changeColor2(id) {
this.setState({
color2: id
});
}
changeColor3(id) {
this.setState({
color3: id
});
}
saveScheme() {
alert("see notes in the function");
// hey guys thanks for looking at my code,
// so what im trying to, is to get all 3
// current colors thats been seleceted.
// pass them over to "saved page", and show them there,
// each time you click "save selection" button,
// it will show the NEW CURRENT selection in the saved page.
// but will NOT delete the previos selection, just add a new one
// kind a like Add To Cart button!
}
render() {
return (
<div className="container">
{this.state.page === "main" && (
<div>
<div className="main-colors">
<div
className="color"
style={{ backgroundColor: this.state.color1 }}
>
<h1>color 1</h1>
</div>
<div
className="color"
style={{ backgroundColor: this.state.color2 }}
>
<h1>color 2</h1>
</div>
<div
className="color"
style={{ backgroundColor: this.state.color3 }}
>
<h1>color 3</h1>
</div>
</div>
<div className="buttons-container">
<p>change color 1:</p>
<Buttons1 changeColor1={this.changeColor1} />
<p>change color 2:</p>
<Buttons2 changeColor2={this.changeColor2} />
<p>change color 3:</p>
<Buttons3 changeColor3={this.changeColor3} />
</div>
<div className="btns">
<button onClick={() => this.saveScheme()}>save selection</button>
<button onClick={() => this.changeToSavedPage()}>
go to saved page
</button>
</div>
</div>
)}
{/* saved page */}
{this.state.page === "saved" && (
<Saved goToMainPage={this.goToMainPage} />
)}
</div>
);
}
}
export default Main;
saved page:
import React from "react";
import "./saved.styles.scss";
import SavedPiece from "../saved-piece/saved-piece.component";
class Saved extends React.Component {
constructor(props){
super(props);
// this.num = this.props.isClicked;
this.state = {
}
}
render(){
return(
<div className="saved-container">
<h1>saved</h1>
{/*
here we should see the saved combinations....
*/}
</div>
)
}
}
export default Saved;
import React from "react";
const Saved = (props) => {
const {saved} = props
return (
<>
<div className="saved-container">
<h1>saved matches page</h1>
{
saved && saved.map((obj, i) => {
return <div className="main-colors" key = {i}>
<div
className="color"
style={{ backgroundColor: obj.color1 }}
>
<h1>color 1</h1>
</div>
<div
className="color"
style={{ backgroundColor: obj.color2 }}
>
<h1>color 2</h1>
</div>
<div
className="color"
style={{ backgroundColor: obj.color3 }}
>
<h1>color 3</h1>
</div>
</div>
})
}
<button onClick={() =>
props.goToMainPage()}>
back to main page
</button>
</div>
</>
)
}
export default Saved;
import React from "react";
import React from "react";
import "./main.style.css";
import Buttons1 from "../buttons/buttons1-component";
import Buttons2 from "../buttons/buttons2-component";
import Buttons3 from "../buttons/buttons3-component";
import Saved from "../saved/saved.component";
class Main extends React.Component {
constructor(props) {
super(props);
this.changeColor1 = this.changeColor1.bind(this);
this.changeColor2 = this.changeColor2.bind(this);
this.changeColor3 = this.changeColor3.bind(this);
this.changeToSavedPage = this.changeToSavedPage.bind(this);
this.goToMainPage = this.goToMainPage.bind(this);
this.saveScheme = this.saveScheme.bind(this);
this.state = {
color1: "#fff285",
color2: "#38306b",
color3: "#c4cc90",
page: "main",
saved: []
};
}
changeToSavedPage() {
this.setState({ page: "saved" });
}
goToMainPage() {
this.setState({ page: "main" });
}
changeColor1(id) {
this.setState({
color1: id
});
}
changeColor2(id) {
this.setState({
color2: id
});
}
changeColor3(id) {
this.setState({
color3: id
});
}
saveScheme() {
const { color1, color2, color3 } = this.state
this.setState({
saved: [
...this.state.saved,
{
color1,
color2,
color3
}
]
})
}
render() {
return (
<div className="container">
{this.state.page === "main" && (
<div>
<div className="main-colors">
<div
className="color"
style={{ backgroundColor: this.state.color1 }}
>
<h1>color 1</h1>
</div>
<div
className="color"
style={{ backgroundColor: this.state.color2 }}
>
<h1>color 2</h1>
</div>
<div
className="color"
style={{ backgroundColor: this.state.color3 }}
>
<h1>color 3</h1>
</div>
</div>
<div className="buttons-container">
<p>change color 1:</p>
<Buttons1 changeColor1={this.changeColor1} />
<p>change color 2:</p>
<Buttons2 changeColor2={this.changeColor2} />
<p>change color 3:</p>
<Buttons3 changeColor3={this.changeColor3} />
</div>
<div className="btns">
<button onClick={() => {
console.log(this.state.saved)
this.saveScheme()
}}>save selection</button>
<button onClick={() => {
this.changeToSavedPage()
}}>
go to saved page
</button>
</div>
</div>
)}
{/* saved page */}
{this.state.page === "saved" && (
<Saved
goToMainPage={this.goToMainPage}
saved = {this.state.saved}
/>
)}
</div>
);
}
}
export default Main;
We added an array to our main component state called saved, then when a user saves, we update the state by adding the values of the current selections, and using the spread operator to maintain the old selected values and not mutate them. Then we pass our saved array as a prop to our child component, and we map it.
How can I rotate the arrows onclick
This is my code below for my react collapse and I would like to rotate the arrows of my collapse accordion when it clicked.
I'm using reactstrap to build it and react fontawsome for my Icons
I've also attached a .GIF Link to demonstrate how my accordion is currently functioning.
import React, { Component } from "react";
import { Collapse, CardBody, Card, CardHeader } from "reactstrap";
import { faChevronDown } from "#fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
const nested = [
{
id: 10,
title:"Customer Queries"
},
];
const Icon = <FontAwesomeIcon icon={faChevronDown} color={"#EB8C00" } />;
class Colapse extends Component {
constructor(props) {
super(props);
this.tog = this.tog.bind(this);
this.state = {
col: 0,
cards: [
{
id:1,
title:"General information requests",
sub_title:"Fault reports",
body:"Something to display for body 1",
},
{
id:2,
title:"Account queries",
sub_title:"Communication protocols",
body:"Something to display for body 2",
}
] };
}
tog(e) {
let event = e.target.dataset.event;
this.setState({
col: this.state.col === Number(event) ? 0 : Number(event),
});
}
render() {
const { col, cards } = this.state;
return (
<div className="container collapse-container">
{nested.map((element, index) => {
return (
<Card key={index} className="card rounded ">
<CardHeader
className="card-header"
onClick={this.tog}
data-event={(index = element.id)}
>
<p className="collapse d-flex">
<div className=" p-2 mr-auto font-weight-bold">
<p className="">{element.title}</p>
</div>
<a
class="click-layer"
onClick={this.tog}
data-event={index}
></a>
</p>
</CardHeader>
<Collapse isOpen={col !== index}>
<CardBody className="card-body">
<p className="card-text">Customer Queries relate to information, account or meter related faults reported by the customer.</p>
{/**HERE NESTED */}
{cards.map((index) => {
return (
<Card key={index} className="card-sub rounded ">
<p className="card-header-sub" >{index.title}</p>
<CardHeader
className="card-header-sub"
onClick={this.tog}
data-event={index.id}
>
<p className="colle d-flex">
<div className="p-2 rotate">{Icon}</div>
<div className=" p-2 mr-auto font-weight-bold">
<p className="card-header-sub">{index.sub_title}</p>
</div>
<a
class="click-layer"
onClick={this.tog}
data-event={index.id}
></a>
</p>
</CardHeader>
<Collapse isOpen={col === index.id}>
<CardBody className="card-body-sub">
<p className="card-text-body">{index.body}</p>
</CardBody>
</Collapse>
</Card>
);
})}
{/**End Of Nested */}
</CardBody>
</Collapse>
</Card>
);
})}
</div>
);
}
}
export default Colapse;
Rotate the svg according to some condition e.g. col === element.id
<div className={`p-2 rotate ${col === element.id ? "isRotated" : ""}`}>{Icon}</div>
on your stylesheet:
.isRotated svg {
transform: rotate(-90deg);
}
My app.js creates a widget layout, within it I have an handleWidgetSelection function which should take an id when an item is clicked in my modal component. When I console log in the handleWidgetSelection function I notice that the state is not updated and it remains null as I originally set it as. I am fairly new to react so any help would be great.
This is my app.js
class App extends Component {
constructor(props) {
super(props);
this.state={
selectedWidgetId: null, //initially set as null because no widget is selected
widgetOptions:[{name:"Data Table", comp:<DataTable/>},{name:"List", comp:<CheckboxList/>}],
widgets:[ //array for layout
{id:1, content: <DataTable/>},
{id:2, content: <CheckboxList/>},
{id:3, content: ""},
{id:4, content: ""}
],
isModalOpen: false
}
}
handleWidgetSelection=(id) => {
this.setState({selectedWidgetId: id})
console.log(this.state.selectedWidgetId); //trying to fix so this value does not always print null
}
.....
render() {
const { classes } = this.props;
return (
<div className={classes.root}>
//I am passing my values to the AddWidgetDialog component here
<AddWidgetDialog handleWidgetSelection={this.handleWidgetSelection} widgets={this.state.widgetOptions} isModalOpen={this.state.isModalOpen} onRequestClose={this.onRequestClose} />
<Grid container spacing={24}>
{
this.state.widgets.map((widget,index)=>{
return(
<Grid item xs={12} sm={6}>
<Paper className={classes.paper}><Swappable id={widget.id} content={widget.content} delete={this.deleteEvent.bind(this,index)} add={this.addEvent.bind(this,index)}/></Paper>
</Grid>
)
})
}
</Grid>
</div>
);
}
This is my AddWidgetDialog component
import React, { PropTypes } from 'react';
import Modal from 'react-modal';
const AddWidgetDialog = ({ handleWidgetSelection, widgets, isModalOpen, onRequestClose}) => {
const widgetItems = widgets.map((widget) => {
return (
<div className="list-group">
<a href="#" onClick={() => handleWidgetSelection(widget.name)} className="list-group-item">
<h6 className="list-group-item-heading">{widget.name}</h6>
</a>
</div>
);
});
return (
<Modal
className="Modal__Bootstrap modal-dialog"
isOpen={isModalOpen}>
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" onClick={onRequestClose}>
<span aria-hidden="true">×</span>
<span className="sr-only">Close</span>
</button>
<h4 className="modal-title">Add a widget</h4>
</div>
<div className="modal-body">
<h5>Pick a widget to add</h5>
{widgetItems}
</div>
<div className="modal-footer">
<button type="button" className="btn btn-default" onClick={onRequestClose}>Close</button>
</div>
</div>
</Modal>
);
};
export default AddWidgetDialog;
setState maybe asynchronous. See the docs Why is setState giving me the wrong value?
handleWidgetSelection=(id) => {
this.setState({selectedWidgetId: id})
console.log(this.state.selectedWidgetId); //no guarantee state is updated or not.
}
You should use console.log() in the callback as second argument to the setState
handleWidgetSelection=(id) => {
this.setState({selectedWidgetId: id},() => {
console.log(this.state.selectedWidgetId); //state is updated now.
})
}
Wondering if I could get some help. I'm building a job board and I'm using github jobs as my jobs API feed. Here's a codesandbox link to my project so far:
https://codesandbox.io/s/34kzz5k6k1
(You need CORS chrome plugin to make the api work).
Basically:
In my index.js file, I'll calling the API in my 'ComponentDidMount'.
And by default, jobs appear for 'New York, on my page.
When you search for 'developer' jobs in 'london', in my 'HandleSubmit', you can see I'm pushing the results to a new URL '/jobresults'.
I'm using browser router to do this.
The problem I'm having though. So my default jobs are still appearing on /jobresults. As well as my 'London' search results, which appear underneath.
How do I only make 'london' jobs appear on this page?
I thought I could try and build a job board all front end. But now I'm think I need REST routing on the backend as well?
Maybe saving my API call in a database. And then displaying the results on a 'show' route?
Any guidance you can give, would be great!
Thanks.
There's a lot going on here that really needs to be revised. The way you've structured the app is anti-pattern (non-stardard/bad practice) and will cause you more headaches as the application becomes more dynamic.
I've gone ahead and restructured the entire app. I encourage you to deconstruct it and follow the application flow, and then take your project and fix it accordingly.
Working example: https://codesandbox.io/s/v873j0600y (still requires CORS extension)
index.js
import React from "react";
import { render } from "react-dom";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import JobForm from "./components/JobForm";
import JobResults from "./components/JobResults";
import NavHeader from "./components/NavHeader";
import "uikit/dist/css/uikit.min.css";
import "./styles.css";
const App = () => (
<main>
<BrowserRouter>
<section>
<NavHeader />
<Switch>
<Route exact path="/" component={JobForm} />
<Route path="/jobs" component={JobResults} />
<Route path="/jobresults/:id" component={JobResults} />
</Switch>
</section>
</BrowserRouter>
</main>
);
render(<App />, document.getElementById("root"));
NavHeader.js
import React from "react";
import { Link } from "react-router-dom";
export default () => (
<header>
<nav>
<ul style={{ listStyleType: "none" }}>
<li style={{ display: "inline", marginRight: 20 }}>
<Link to="/">Home</Link>
</li>
<li style={{ display: "inline", marginRight: 20 }}>
<Link to="/jobs">Jobs</Link>
</li>
</ul>
</nav>
</header>
);
JobForm.js
import React, { Component } from "react";
export default class JobForm extends Component {
state = { searchData: "", cityData: ""};
// HANDCHANGE FOR JOB SEARCH
handleChange = e => this.setState({ searchData: e.target.value });
// HANDLE CHANGE FOR LOCATION SEARCH
handleChangeLocation = e => this.setState({ cityData: e.target.value });
// HANDLE SUBMIT
handleSubmit = e => {
e.preventDefault();
const { cityData, searchData } = this.state;
if (!cityData || !searchData) return;
this.props.history.push(
`/jobresults/positions?description=${searchData}&location=${cityData}`
);
};
render = () => (
<section className="hero homepage">
<div className="container">
<h1 className="title has-text-white">USA Creative City</h1>
<h2 className="title has-text-white">Start your job search here!</h2>
<form className="level-item" onSubmit={this.handleSubmit}>
<div className="inputstyle field has-addons">
<div className="control ">
<input
className="uk-input"
type="text"
placeholder="Software Engineer..."
onChange={this.handleChange}
style={{ width: 200 }}
/>
</div>
<div className="control ">
<input
className="uk-input"
type="text"
placeholder="City"
onChange={this.handleChangeLocation}
style={{ width: 200 }}
/>
</div>
<div className="control">
<button
style={{ width: 200 }}
className="uk-button uk-button-primary"
>
<i
style={{ marginRight: 10 }}
className="fas fa-search"
aria-hidden="true"
/>Search Jobs
</button>
</div>
</div>
</form>
</div>
</section>
);
}
JobResults.js
import isEmpty from "lodash/isEmpty";
import React, { Component, Fragment } from "react";
import axios from "axios";
import qs from "qs";
import Spinner from "./Spinner";
import ShowResults from "./ShowResults";
import NoResults from "./NoResults";
const getRandomInt = max => Math.floor(Math.random() * Math.floor(max));
const locations = ["Los Angeles", "New York", "San Mateo", "San Francisco"];
const descriptions = ["Developer", "Engineer", "MySQL", "MongoDB"];
export default class JobResults extends Component {
state = { isLoading: true, jobs: [], error: "" };
componentDidUpdate = (prevProps, prevState) => {
if (this.props.location.pathname !== prevProps.location.pathname) {
this.setState({ isLoading: true }, () => this.fetchData());
}
};
componentDidMount = () => this.fetchData();
fetchData = () => {
let { description, location } = qs.parse(this.props.location.search, {
ignoreQueryPrefix: true
});
if (!description || !location) {
description = descriptions[getRandomInt(3)];
location = locations[getRandomInt(3)];
}
axios(`https://jobs.github.com/positions.json?description=${description}&location=${location}`)
.then(({ data }) => this.setState({ isLoading: false, jobs: data.slice(0, 9) }))
.catch(err => this.setState({ isLoading: false, err: err.toString() }));
};
render = () =>
this.state.isLoading
? <Spinner />
: <section>
<h3 style={{ textAlign: "center" }} className="has-text-centered animated shake slow">
RESULTS
</h3>
<div className="columns is-multiline">
{isEmpty(this.state.jobs)
? <NoResults err={this.state.err} />
: <ShowResults jobs={this.state.jobs} />
}
</div>
</section>
);
}
ShowResults.js
import map from "lodash/map";
import React from "react";
export default ({ jobs }) => (
map(jobs, ({ id, created_at, company_logo, title, company, location, url }) => (
<div className="result" key={id}>
<img className="image" src={company_logo} />
<h4 className="has-text-left purple">Location: {title}</h4>
<h5 className="has-text-left purple">
Created on: {created_at}
</h5>
<h5 className="has-text-left purple">Company: {company}</h5>
<h5 className="has-text-left purple">Location: {location}</h5>
<a className="uk-button uk-button-primary" href={url} target="_new">
apply on github
</a>
<a
className="uk-button uk-button-primary"
style={{ marginTop: 10 }}
href={url}
target="_new"
>
apply on creative jobs
</a>
</div>
)
);
NoResults.js
import React from "react";
export default ({ err }) => (
err
? <p style={{ textAlign: "center", color: "red" }}>
<i style={{ marginRight: 5 }} className="fas fa-exclamation-circle" />
{err}
</p>
: <p style={{ textAlign: "center", color: "grey" }}>
<i style={{ fontSize: 22, marginRight: 5 }} className="far fa-calendar-times"/>
No jobs matching that criteria.
</p>
);
Spinner.js
import React from "react";
const spinners = () => {
let children = [];
for (var i = 1; i < 13; i++) {
children.push(<div key={i} className={`sk-circle${i} sk-circle`} />);
}
return children;
};
export default () => <div className="sk-fading-circle">{spinners()}</div>;
Tried to add two buttons, one to add item(increment the quantity count) and other to delete item(decrements quantity count) to update the quantity parameter. When i click on the add item button of one product, the quantity of all the products is getting updated. How to make these buttons work independently for each product?
Below is the code i wrote:
import React from 'react';
import ReactDOM from 'react-dom';
import Paper from 'material-ui/Paper';
import products from './Products';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn, } from 'material-ui/Table';
const style = {
height: 600,
width: 900,
margin: 20,
textAlign: 'center',
display: 'inline-block',
};
export default class Cart extends React.Component{
constructor(props){
super(props);
this.state={ count:1 }
}
addOne(id) { // addOne one item when button clicked
this.setState(prevState => {
return {count : prevState.count + 1 }
});
}
removeOne(id) { // removeOne one item when button clicked
this.setState(prevState => {
if(prevState.count>=1) {
return { count : prevState.count - 1 }
}
else{
alert('quantity cant be less than zero')
}
});
}
render(){
return(
<div>
<Paper style={style} zDepth={1} >
<div>
<div>
<h3> here are the products ! </h3>
</div> <hr/>
<div>
{Products.map(productlist =>(
<Table >
<TableHeader displaySelectAll={false} adjustForCheckbox={false} >
<TableRow>
<TableHeaderColumn></TableHeaderColumn>
<TableHeaderColumn></TableHeaderColumn>
<TableHeaderColumn></TableHeaderColumn>
<TableHeaderColumn></TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody displayRowCheckbox={false} >
<TableRow key={productlist.id}>
<TableRowColumn>{productlist.name}</TableRowColumn>
<TableRowColumn>{productlist.description}</TableRowColumn>
<TableRowColumn>{productlist.description}</TableRowColumn>
<TableRowColumn>Price per each item:<br/> {productlist.price}</TableRowColumn>
<TableRowColumn>
<input type='button' onClick={this.addOne.bind(this,productlist.id)} value='add an item'/>
<input type='button' onClick={this.removeOne.bind(this,productlist.id)} value='remove an item'/>
<br/> <span> quantity: {this.state.count} </span>
</TableRowColumn>
</TableRow>
</TableBody>
</Table>
))}
</div>
<div>
<p> Total price: </p>
</div>
</div>
</Paper>
</div>
);
}
}
Below is the sample Product.js code:
let Products=[
{
id:1, name:"Fastrack Women's Watch",
description:"Analog Pink Dial Women's Watch - 6150SM04",
price:2500
},
{
id:2, name:"Fastrack Women's Watch",
description:"Analog Pink Dial Women's Watch - 6150SM04",
price:2100
},
{
id:3, name:"Fastrack Women's Watch",
description:"Analog Pink Dial Women's Watch - 6150SM04",
price:1800
},
];
export default Products;
I would recommend you rethink the design of your program abit. In my opinion you should move the individual product to its own component and then that would have a state too. So, remove the state from the Cart and create a component and name it as Product. This Product component would be a child component of Cart. If you need to update something in Cart from Product then you could use callback.
So something like
class Cart extends React.Component {
render(){
<..>
{products.map(product => {
// New shiny component with state
return <Product {...props} />
})}
<..>
}
}
Hope this helps!