score:0
i would update your code and split it into two components, a list component and an item component (in this case pizza?). the list component would provide a method for modifying the list using the context api. in my example, i have an updatepizza
method that i pass down in the context.
then, in the child component, you have a click handler that updates the occupied
status of the pizza and tells the parent what the new status is using the context method.
this makes sure that the parent component always has the current state for all the pizzas and passes that down to the children. the parent component becomes the single source of truth here.
class list extends react.component {
static childcontexttypes = {
updatepizza: react.proptypes.func
}
constructor({ pizzas }){
super()
this.state = { pizzas }
}
updatepizza = (idx, pizza) => {
this.setstate( ({ pizzas }) => {
pizzas[idx] = pizza;
return { pizzas }
})
}
getchildcontext() {
return { updatepizza: this.updatepizza }
}
render(){
return <ul>{this.state.pizzas.map((pizza, idx) => <pizza key={ idx } { ...pizza }>)}<ul>
}
}
class pizza extends react.component {
static contexttypes = {
updatepizza: react.proptypes.func
}
handleclick = () => {
this.state.occupied = !this.state.occupied;
this.context.updatepizza(this.state.key, this.state)
}
render() {
const { key, seat, row, occupied } = this.state;
const status = occupied ? 'coloring' : 'colored';
return <li key={ key } classname={ status } onclick={ handleclick }> seat: { seat } { row }</li>
}
}
score:1
i created a simple example of how you can update your code, also with two components (similar to the idea by @thethechad), but without using context
since according to react docs it is discouraged to use context
directly if you want your app to be stable. if state
and props
management in app gets too complicated you can include redux
(which internally also uses context
), but for now i am not including redux
since it be might over-complication in this simple case.
here is pizzalist
which has pizzas
on its state
. the component will render pizzaitem
components and pass a callback down so that each pizzaitem
can notify its parent (pizzalist
) when it is clicked. pizzalist
has the responsibility of toggling pizzaitem
when it is clicked.
class pizzalist extends react.purecomponent {
state = {
pizzas: []
}
componentdidmount() {
// fetch data about pizzas via an api and perform this.setstate
this.setstate({ pizzas: [{ seat: 20, occupied: false }, { seat: 10, occupied: true }, { seat: 30, occupied: true }] });
}
handlepizzaitemclick = (pizzaind) => {
this.setstate((prevstate) => {
// find clicked pizza and toggle its occupied property
const pizzas = prevstate.pizzas.map((pizza, ind) => {
if (ind === pizzaind)
return { ...pizza, ...{ occupied: !pizza.occupied } };
return pizza;
});
return { pizzas: pizzas };
});
}
render () {
return (
<ul>
{this.state.pizzas.map((pizza, index) =>
<pizzaitem
onclick={this.handlepizzaitemclick}
index={index}
pizza={pizza}
/>)}
</ul>
);
}
}
pizzaitem
is a simple function component that doesn't have any state.
const pizzaitem = ({ index, pizza, onclick }) => {
const { seat, row, occupied } = pizza;
const pizzaclassname = occupied ? 'coloring' : 'colored';
return (
<li key={index}
classname={pizzaclassname}
onclick={() => onclick(index)}>
seat: {seat} {row}
</li>
);
}
here is a working example on codesandbox.
Source: stackoverflow.com
Related Query
- REACT - toggle class onclick
- Toggle Class in React
- Toggle Class based on scroll React JS
- React toggle class + CSS transitions, not working... why?
- React State Hook - toggle a class
- How to toggle class for the only one element on click in react
- Toggle css class in React
- How to toggle css class of a single element in a .map() function in React
- How to toggle class on mousedown/mouseup in react component?
- React toggle active class on click of anchor using Gatsby Js
- toggle class on multiple elements react
- Add toggle class to div in React
- Toggle active class for the child or its relevant siblings onClick in React
- React js onclick toggle class in map function
- How to toggle css class on React
- React Toggle Active Class between multiple Reactstrap Buttons
- How to toggle class of a div element by clicking on button in react js?
- React Js: Getting and error in if else statement Line 50:20: Parsing error: Unexpected token, expected ","
- Toggle Show/Hide `active` class on li's in react js
- Toggle class except if a child is clicked in React
- Unable to toggle class on onClick in React
- How to toggle a class on the body with React onClick
- React toggle active class between button group array
- add active class On react with out state and toggle using JS dom
- How to toggle class using React Hooks as per localstorage value in App.js?
- if else statement not working in react component
- React - toggle text and class in an HTML element?
- Toggle body class with styled-components and React setState
- React - toggle css class
- React toggle class on just one component
More Query from same tag
- I can't modify my SVG component in my React Application
- ReactJS: Using one button in child component disables a second button?
- Pure reactJS: Game of Life rules are displayed wrong due to float:left grid building not corresponding with 2d Array
- ReactJS PreventDefault when already passing parameter
- React Native Circle Image on Android
- Electron-compile how to use scss or at least css with react?
- Use reselect selector with parameters
- Converting object to array to map over
- How to use React useCallback and useEffect with outside dependencies
- ReactJs error - Warning: setState(...): Can only update a mounted or mounting component
- Syntax error in IE11 with Webpack, Babel and React
- Refactoring class component to functional component with hooks, getting Uncaught TypeError: func.apply is not a function
- React Native WebView Loading Error Handling
- How do I include embed code with an external script in the body of a Gatsby site?
- @material-ui icons not displaying on the screen
- Trying to retrieve an mp3 file stored in AWS S3 and load it into my React client as a Blob...it's not working
- convert object of 3 keys to array
- Setting states of array element in React
- Trying to re-render after store update via redux
- React calling another component
- How to pass an array with multiple values in the body of jsPDF?
- How to make exe file from Reactjs and a nodejs app?
- Map typescript parameter: Binding element 'columns' implicitly has an 'any' type
- Module build failed: SyntaxError: Unexpected token regarding quotation marks
- How to manage dynamic variables from external config file using Electron and React
- React-Leaflet: Placing map control components outside of map?
- ReactJS - how to fetch inside a child component with details passed on by props from a parent component?
- Previous and current state are equal in componentDidUpdate
- Is it possible to dynamically adjust the data cells of columns in order for them to appear on the same vertical line?
- prevent asking "Missing JSDoc comment" for standard react methods in typescript project