Reload table after deleting an item from it with React - javascript

Using React.Js, I created a delete function to delete an item from a table. the delete is working fine but what I want to do is that after deleting I want the tables to be dynamically updated to show only the items left. Now after the delete I have to refresh manually the page or go to another page and comeback to see the items left after the delete
This is the code built so far :
import React, { Component } from "react";
import { Card, Button, Select,/* message, */ Form, Tooltip } from "antd";
import extraitMP3 from "./data";
import { arrayMove, SortableHandle } from "react-sortable-hoc";
import ContainerHeader from "components/ContainerHeader/index";
import { getExtraitMp3, hideMessageUpdate, showUpdateLoader, updateMp3Visibilite } from "appRedux/actions/Comedien";
import { deleteMp3Request } from "../../../appRedux/services/extraitMp3Service"
import { connect } from "react-redux";
import { NotificationContainer, NotificationManager } from "react-notifications";
import { userSignOut } from "appRedux/actions/Auth";
import { displayIcon } from '../../../util/Icon.js';
import CircularProgress from "components/CircularProgress";
import { Modal } from "antd";
const extraitMP32 = [extraitMP3];
const confirm = Modal.confirm;
const Option = Select.Option;
const DragHandle = SortableHandle(() =>
<span className="gx-draggable-icon gx-pt-2">
<i className="icon icon-menu" style={{ fontSize: 25 }} />
</span>);
class ListExtrait extends Component {
onSortEnd = ({ oldIndex, newIndex }) => {
this.setState({
extraitMP3: arrayMove(this.state.extraitMP3, oldIndex, newIndex),
});
};
constructor() {
super();
this.state = {
extraitMP3: extraitMP32[0],
nombreMP3: {
rechercheExtraits: 0,
recherchePossible: 0,
extraitFiche: 0,
extraitFichePossible: '',
extraitArchives: 0,
extraitArchivesPossible: '',
},
loader: false,
}
}
componentDidMount() {
this.props.getExtraitMp3();
}
componentDidUpdate() {
}
static getDerivedStateFromProps(nextProps, prevState,/* nextProps2,prevState2 */) {
if (nextProps.extraitMP3 !== prevState.extraitMP3 && nextProps.extraitMP3) {
return { extraitMP3: nextProps.extraitMP3 };
}
else return null;
}
showDeleteConfirmation(value, id, index, thisHandler) {
confirm({
title: 'Voulez vous supprimer cette audio ?',
content: '',
okText: 'Oui, je confirme',
okType: 'danger',
cancelText: 'Non',
onOk() {
deleteMp3Request(id);
const { extraitMP3 } = thisHandler.state;
Object.keys(extraitMP3).splice(index, 1);
NotificationManager.success("le fichier audio est supprimé avec succès !", "");
},
onCancel() {
},
});
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
this.props.showUpdateLoader();
this.props.updateMp3Visibilite(values);
}
});
};
render() {
const { loader, extraitMP3 } = this.state;
const selectOptions = new Map([
[1, "Visible dans la recherche et sur ma fiche"],
[2, "Visible sur ma fiche uniquement"],
[3, "Masqué"],
]);
console.log('extraitMP3', extraitMP3)
function handleChangeSelect(value) {
console.log(`selected ${value}`);
}
return (
<div>
{loader ? <CircularProgress className="gx-loader-400" /> : Object.keys(extraitMP3).map((ids, index) => {
return (
<Card>
<li key={ids}>
<Card styleName="gx-card-list icon icon-data-display gx-mr-2 gx-text-blue gx-fs-xl">
<div className="gx-media-body">
{extraitMP3[ids].Typenom}
{extraitMP3[ids].TypeIcon != null &&
displayIcon(extraitMP3[ids].TypeIcon)
}
</div>
{Object.keys(extraitMP3[ids].TypeMp3List).map(idJson => {
return (
<div className="gx-main-content gx-mb-4">
<ContainerHeader match={this.props.match} />
<div className="gx-contact-item gx-dragndrop-item">
<DragHandle />
<div className="gx-col gx-job-title ">
{extraitMP3[ids].TypeMp3List[idJson].intitule}
</div>
{extraitMP3[ids].TypeMp3List[idJson].interpretation1Icon !== '' &&
<Tooltip title={extraitMP3[ids].TypeMp3List[idJson].interpretation1Nom}>
{displayIcon(extraitMP3[ids].TypeMp3List[idJson].interpretation1Icon)}
</Tooltip>
}
{extraitMP3[ids].TypeMp3List[idJson].interpretation2Icon !== '' &&
<Tooltip title={extraitMP3[ids].TypeMp3List[idJson].interpretation2Nom}>
{displayIcon(extraitMP3[ids].TypeMp3List[idJson].interpretation2Icon)}
</Tooltip>
}
{extraitMP3[ids].TypeMp3List[idJson].interpretation3Icon !== '' &&
<Tooltip title={extraitMP3[ids].TypeMp3List[idJson].interpretation3Nom}>
{displayIcon(extraitMP3[ids].TypeMp3List[idJson].interpretation3Icon)}
</Tooltip>
}
{extraitMP3[ids].TypeMp3List[idJson].langueIcon !== '' &&
<div className="gx-col gx-job-title gx-d-sm-flex gx-text-truncate gx-px-8">
<Tooltip title={extraitMP3[ids].TypeMp3List[idJson].langueNom}>
<i className={`flag flag-24 gx-mr-2 ${extraitMP3[ids].TypeMp3List[idJson].langueIcon}`} />
</Tooltip>
</div>
}
<div className="gx-col gx-job-title gx-d-sm-flex gx-text-truncate gx-px-8">
<Select
showSearch
style={{ width: '100%' }}
placeholder="Selection la choix de votre numéro de téléphone "
optionFilterProp="children"
onChange={handleChangeSelect}
defaultValue={selectOptions.get(extraitMP3[ids].TypeMp3List[idJson].visibilite)}
filterOption={(input, Option) => Option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
>
{[...selectOptions].map(([value, label]) => <Option value={value}> {label} </Option>)}
</Select>
</div>
<div className="gx-col gx-job-title gx-d-sm-flex gx-text-truncate gx-px-8">
<i className="icon icon-edit gx-fs-xl gx-text-gris" />
</div>
<div className="gx-col gx-job-title gx-d-sm-flex gx-text-truncate gx-px-8">
<span className="gx-pointer">
<i className="icon icon-trash gx-pointer gx-text-danger gx-fs-xxl"
id={extraitMP3[ids].TypeMp3List[idJson].id}
onClick={e => this.showDeleteConfirmation(e.target.value, extraitMP3[ids].TypeMp3List[idJson].id, index, this)} />
</span>
</div>
</div>
</div>
)
})}
<NotificationContainer />
<Button type="primary" htmlType="submit" labelCol={{ xs: 24, sm: 5 }} wrapperCol={{ xs: 24, sm: 12 }}>
Enregistrer
</Button>
</Card>
</li>
</Card>
)
})}</div>
)
}
}
const VisibiliteFormMp3 = Form.create()(ListExtrait);
const mapStateToProps = ({ comedien }) => {
const {
extraitMP3,
alertMessageUpdate,
showMessageUpdate
} = comedien;
return {
extraitMP3,
alertMessageUpdate,
showMessageUpdate
}
};
export default connect(
mapStateToProps,
{
userSignOut,
getExtraitMp3,
hideMessageUpdate,
showUpdateLoader,
updateMp3Visibilite
})(VisibiliteFormMp3);
extraitMP3 is an object of objects that's why I used Object.keys(extraitMP3)
I didn't know how to update the state correctly.
this is the view :

You should put your data in state and then change the state. After changing the state the page automatically re-rendered and changed data of your state will be shown.
So in your delete function simply delete your chosen data and give your remaining data to your state.
Hope this helps, feel free to ask questions if I couldn't explain myself clearly.

I believe you can do this by calling something like and then just call this from within your delete
refreshMp3(){
this.setState({getExtraitMp3: !this.state.getExtraitMp3});}

One of the ideas of React is to make the functionality you ask for simple to implement and it would update automatically. I'm going to abstract a bit from your example. Think about your data in terms of what updates along with the UI. This way we can simplify your component. You have some items that you put in a table. Each item is a row and can be inside an array. We put that array in the state.
class ListExtrait extends Component {
constructor() {
super();
this.state = {
rowsForTable: [...],
somethingElse...
}
...
Then in the JSX in the render method you can render the table rows using map:
rowsForTable.map(item => <div/li/whatever>{item.name or something else}</div>
This way whenever an item is gone from rowsForTable the component will automatically update it's view and the table rows will be up to date.

You can simply call the function while clicking the delete button say deleteHandler. On that function call the api you have made to delete the item and then after successfull delete again call the api that will show the item from database after certain time interval.
Code:
import React, { Component } from 'react'
export default class show_schedule extends Component {
render() {
state={
}
show_item_after_delete=()=>{
setTimeout(()=>{
axios.get(`http://127.0.0.1:8000/account/api/show_item/`).then(res=>{
console.log('delete schedule data ',res.data)
})
},500)
}
deleteHandler=()=>{
axios.delete(`http://127.0.0.1:8000/account/api/delete_item/${id}`).then(res=>{
console.log(res.data)
})
this.show_item_after_delete()
}
return (
<div>
<button onClick={this.deleteHandler}>Delete</button>
</div>
)
}
}

Related

Ternary operator not working as desired on state change

I'm trying to build a map that will show whisky distilleries as icons on the map. When one of the distillery markers is clicked, the state is updated to hold an object with that distillery data so a popup can render with relevant info. I've got a hover effect that I want to persist after clicking for as long as the state holds the obj.
I have the following ternary operator that should add 'clicked' when selectedDistillery is truthy, but the class is not applied.
className={`marker-btn ${selectedDistillery ? 'clicked' : ''}`}
The popup renders fine on click so not really sure what the issue is.
Here's the entire component
import 'mapbox-gl/dist/mapbox-gl.css';
import './App.css';
import React, { useState, useEffect } from 'react'
import ReactMapGl, { Marker, Popup } from "react-map-gl";
import * as distilleries from "./data/dist-locations.json";
const App = () => {
const [viewport, setViewport] = useState({
latitude: 56.770720743612365,
longitude: -4.2724397531559655,
width: "90vw",
height: "90vh",
zoom: 6,
});
const [selectedDistillery, setSelectedDistillery] = useState(null);
useEffect(() => {
const listener = (e) => {
if(e.key === 'Escape'){
setSelectedDistillery(null);
}
}
window.addEventListener('keydown', listener);
return () => {
window.removeEventListener('keydown', listener);
}
}, [])
console.log(selectedDistillery);
return (
<div className="main-container">
<div className="map-container">
<ReactMapGl
{...viewport}
mapboxApiAccessToken={process.env.REACT_APP_API_KEY}
onViewportChange={(viewport => { setViewport(viewport) })}
mapStyle="mapbox://styles/vdiad/ckkq0g4201s4r17peswejsg82"
>
{distilleries.features.map(distillery => {
return(
<Marker key={distillery.id} latitude={distillery.geometry.coordinates[1]} longitude={distillery.geometry.coordinates[0]} >
<button
className={`marker-btn ${selectedDistillery ? 'clicked' : ''}`}
onClick={()=>{
setSelectedDistillery(distillery);
}}
>
<img src="/barrel1.svg" alt="whisky barrel img" />
</button>
</ Marker>
)
})}
{selectedDistillery && (
<div className="popup">
<Popup
latitude={selectedDistillery.geometry.coordinates[1]}
longitude={selectedDistillery.geometry.coordinates[0]}
onClose={()=>{setSelectedDistillery(null)}}
>
<h3>{selectedDistillery.properties.NAME}</h3>
<p>Founded in: </p>
<p>Region: </p>
</ Popup>
</div>
)}
</ReactMapGl>
</div>
</div>
)
}
export default App

Edit posts in react

I am trying to edit the text inside my Products component---
import React, { Component } from 'react'
import Newitem from './Newitem'
import App from '../App';
export default class Products extends Component {
state = {
name:this.props.name,
price:this.props.price,
description:this.props.description,
rating:this.props.rating,
img:this.props.img,
newName:'',
newPrice:'',
newDescription:'',
newImg:'',
inputsDisplay:'',
index:this.props.index,
}
deleteFunc=()=>{
this.props.delete(this.state.index)
}
changeName=(e)=>{
let changeNameInput=e.target.value;
this.setState({newName:changeNameInput})
}
changePrice=(e)=>{
let priceInput=e.target.value;
this.setState({newPrice:priceInput})
}
changeDescrip=(e)=>{
}
changeImg=(e)=>{
}
editButton=()=>{
if(this.state.newName.length==0){
this.setState({
inputsDisplay:'block'
})
}
else{
this.setState({
name:this.state.newName,
price:`${this.state.newPrice} NIS`,
inputsDisplay:'block'
})
}
}
hideEditInputs=()=>{
this.setState({inputsDisplay:'none'})
}
render() {
return (
<div className='container' id='Container'>
<span className='namestyle'>{this.props.name}</span>
<span className='descriptionstyle'>{this.props.description}</span>
<img className='imgstyle' alt='Bad source' src={this.props.img}></img>
<span className='pricestyle'>{this.props.price}</span>
<span className='ratingstyle'>{this.props.rating}</span>
<button onClick={this.deleteFunc} id='deleteButton'>X</button>
<input className='editNameInput' onChange={this.changeName} placeholder='Edit name'
style={{display:this.state.inputsDisplay}}>
</input>
<button className='editButton' onClick={this.editButton}>EDIT</button>
<input onChange={this.changePrice} className='editPriceInput' placeholder='Edit price'
style={{display:this.state.inputsDisplay}}>
</input>
<input className='editDescripInput' placeholder='Edit description'
style={{display:this.state.inputsDisplay}}>
</input>
<input className='editImgInput' placeholder='Edit IMG'
style={{display:this.state.inputsDisplay}}>
</input>
<button onClick={this.hideEditInputs}className='hideEditButton' >HIDE EDIT</button>
</div>)
}
}
I have 3 components Products, Header, App, and Newitem.
The Header is for the title, the App holds my data array, Newitem is placing new 'post'(product) inside of my data array, Products get props from App.
I created 4 inputs and my goal is When I click the EDIT button the text in the input will replace the text I got from the props.
I tried with setState but it seems to bug the Newitem function(it's giving me a new product with the same info I have in the data array and not what I gave to the function)
I really clueless about what I did wrong, here are my other components Newitem---
import React, { Component } from 'react'
import Products from './Products'
export default class Newitem extends Component {
state = {
imgInput:'',
discriptionInput:'',
nameInput:'',
priceInput:'',
validNameBG:'white',
validPriceBG:'white',
validDiscriptionBG:'white',
validImgBG:'white'
}
validName=(e)=>{
let nameInput=e.target.value
console.log(nameInput)
if(nameInput.length>=4 && nameInput.length<40){
this.setState({
nameInput:nameInput,
validNameBG:'lightgreen'
})
}
else if(nameInput.length==0){
this.setState({validNameBG:'white'})
}
else{this.setState({
validNameBG:'red',
nameInput:''
})}
}
validPrice=(e)=>{
let priceInput=Number(e.target.value)
if(isNaN(priceInput)){
this.setState({validPriceBG:'red'})}
else if(!isNaN(priceInput)){
this.setState({
priceInput:priceInput,
validPriceBG:'lightgreen'
})
}
if(priceInput === 0){
this.setState({
validPriceBG:'white',
priceInput:'',
})
}
}
validDescription=(e)=>{
let discriptionInputValue=e.target.value
if(discriptionInputValue.length>=4 && discriptionInputValue.length<100){
this.setState({
validDiscriptionBG:'lightgreen',
discriptionInput:discriptionInputValue})
}
else if(discriptionInputValue.length==0){
this.setState({
validDiscriptionBG:'white'
})
}
else{this.setState({
validDiscriptionBG:'red',
discriptionInput:''
})}
}
validImg=(e)=>{
let imgInputValue=e.target.value;
if(imgInputValue.length>7){
this.setState({
validImgBG:'lightgreen',
imgInput:imgInputValue
})
}
else if(imgInputValue.length <= 7 && imgInputValue.length>0){
this.setState({
validImgBG:'red',
imgInput:''
})
}
else{
this.setState({
validImgBG:'white',
imgInput:''
})
}
}
addFunc=()=>{
if(this.state.validDiscriptionBG=='red'||this.state.validImgBG=='red'||this.state.validNameBG=='red'
||this.state.validPriceBG=='red'){
return alert('Invalid value.')
}
else if(this.state.validDiscriptionBG=='white'||this.state.validImgBG=='white'||this.state.validNameBG=='white'
||this.state.validPriceBG=='white'){
return alert('Invalid value.')
}
else{
this.props.add(
this.state.nameInput,
`${this.state.priceInput} NIS`,
this.state.discriptionInput,
this.state.imgInput,
)}
}
render() {
return (
<div>
<ul id='placing '>
<input onChange={this.validName}
id='nameInput' placeholder='Name'
style={{backgroundColor:this.state.validNameBG}}>
</input>
<input onChange={this.validPrice}
id='priceInput' placeholder='Price'
style={{backgroundColor:this.state.validPriceBG}}>
</input>
<button onClick={this.addFunc} className='plusbutton'>Add</button>
</ul>
<ul>
<input onChange={this.validDescription}
id='descriptionInput' placeholder='Description'
style={{backgroundColor:this.state.validDiscriptionBG}}
></input>
<input onChange={this.validImg}
id='imgInput' placeholder='Img Source'
style={{backgroundColor:this.state.validImgBG}}
></input>
</ul>
</div>
)
}
}
App component----
import React, { Component } from 'react'
import Header from './components/Header'
import Products from './components/Products'
import Newitem from './components/Newitem'
import '../src/App.css';;
export default class App extends Component {
state = {
products: [
{
name:'Apple iphone 11 Pro max 256gb',
price:'4749 NIS',
description:'Iphone 11 256 gb,with 4gb ram, 6.5 inch,thickness 8.1',
rating:'5/5 Stars ! ',
img:'https://img.zap.co.il/pics/3/3/2/9/52789233b.gif'
},
{
name:'Samsung Galaxy S20 Plus',
price:'3749 NIS',
description:'Android operation system 8gb of ram Thickness 7.8m,weight 186 gram',
rating:'5/5 Stars !',
img:'https://img.zap.co.il/pics/0/2/1/8/54298120b.gif'
},
{
name:'Xiamo Poco X3',
price:'1265 NIS',
description:'Android operation system 6gb of ram Thickness 9.4m,refresh rate 120Hz',
rating:'3/5 Stars ! ',
img:'https://img.zap.co.il/pics/2/8/3/8/57738382b.gif'
},
{
name:'Samsung Galaxy A71',
price:'1049 NIS',
description: 'Android operation system 6gb of ram ,48 Mega pixel Thickness 7.9m',
rating:'4/5 Stars !',
img:'https://img.zap.co.il/pics/3/1/3/3/53803313b.gif'
}]
}
addNewProduct =(n,p,d,i,r)=>{
const newProduct= {
name:n,
price:p,
description:d,
img:i,
rating:r,
}
this.setState({products:[newProduct,...this.state.products]})
}
deleteProduct=(i)=>{
let filteredProducts=this.state.products.filter((item,index)=>(index!==i))
this.setState({products:filteredProducts})
}
render() {
return (
<div className="App">
<Newitem add={this.addNewProduct}/>
<Header />
{this.state.products.map((item,index)=>{
return(
<Products
name={item.name}
price={item.price}
description={item.description}
rating={item.rating}
img={item.img}
delete={this.deleteProduct}
index={index}
/>
)
})}
</div>
)
}
}
Thank you a lot
Props should be immutable, so a component shouldn't manage is own props. You can do it the same way you are using to delete a product.
This code should be in your App component. Receive the index and update your data.
changeName=(index, e)=>{
const updatedProducts = [...this.state.products];
updatedProducts[index].name = e.target.value;
this.setState({ products: updatedProducts });
}
Then pass the function as a prop to Product component.

How to pass parameters between components in React?

I have to do a CRUD app in React.
I'm using the same form for the Update and Create.
When all data are shown, I click on "update" in a row, I take the ID and redirect to the form.
My problem is for the Create beacause I have a sidebar with the URL and I'm not able to pass the ID parameter so that I can create a condition.
e.g. If(id === null) --> redirect form/ --> else --> redirect form/{id}
dashRoutes.js
//HERE I WANT TO GET THE ID FROM THE LIST BECAUSE "/form_promo/:promoId" works but I can't do any condition.
let dashRoutes = [
{
path: `/form_promo/{promoid}`,
name: "Add Promo",
icon: "ui-1_simple-add",
component: UpdateSinglePromo,
layout: "/admin"
}
];
export default dashRoutes;
index.js
<Route path="/admin/form_promo" component={UpdateSinglePromo}/>
<Route path="/admin/form_promo/:promoId" component={UpdateSinglePromo}/>
PromoCatalogList.jsx
class PromoCatalogList extends React.Component {
constructor(props) {
super(props);
this.state = {
promos: [],
message: null
};
//
//
this.updatePromoClicked = this.updatePromoClicked.bind(this);
this.addPromo = this.addPromo.bind(this);
}
componentDidMount() {
//
}
refreshCourses() {
//
}
switchOffPromo(promoId) {
//
}
addPromo() {
this.props.history.push(`/admin/form_promo`)
}
updatePromoClicked(promoId) {
console.log('update ' + promoId);
this.props.history.push(`/admin/form_promo/${promoId}`)
}
render() {
let promos = this.state.promos.map((item) => ({
update:
<MDBBtn type="button" className="btn btn-outline-success waves-effect"
onClick={() => this.updatePromoClicked(
item.promoId,
item.prizeId,
item.ijCod,
item.title,
item.description,
)}>Update</MDBBtn>,
promoId: item.promoId,
prizeId: item.prizeId,
ijCod: item.ijCod,
title: item.title,
description: item.description,
delete:
<MDBBtn outline color="danger"
onClick={() => this.switchOffPromo(item.promoId)}>OFF</MDBBtn>
}))
;
const data = {
columns: columnsHeaders,
rows: promos
};
return (
<>
<PanelHeader size="sm"/>
<div className="content">
//
<MDBDataTable
striped
bordered
small
data={data}
/>
//
</div>
</>
);
}
}
export default PromoCatalogList
So if the id is not null I would like to show a different name in my dashRoutes.js like "Edit Promo".
In this moment I can show or the empty form "formPromo/" OR the updateForm "formPromo/:promoId", not together.

React updating shopping cart when item selected

I am new to react and I am working on a flight project.
I am attempting to update a shopping cart when items are selected. I am aware the structure of the code might not be the best way, but this is what I have so far.
Export class DestinationPrices extends React.Component {
constructor(props) {
super(props);
this.state = {
flightData: [],
checked:false,
data:'',
cart:[]
};
this.handleClick = this.handleClick.bind(this);
this.handleAddToCart = this.handleAddToCart.bind(this);
}
NavCart() {
return (
<div className="Nav" >
<Card body >
<CardTitle ><h3><b>Flights Selected : </b></h3></CardTitle>
<CardText >
<span className="fa fa-cart-plus fa-2x"> {this.props.cart.length}</span>
</CardText>
</Card>
</div>
)
}
That is the cart itself which should update number of items when selected.
Below is the Select method which you can select the different cards.
Select(FD) {
this.state={route:''};
return (
<div>
{FD.FlightID}
<label>
<Checkbox id={FD.FlightID}
name={FD.FlightID}
checked={this.setState.route}
onChange={(()=> this.handleCheckboxChange(FD.FlightID))}
handleClick={()=>{this.handleClick(FD.FlightID)}}
/>
<span>Select</span>
</label>
</div>
)
}
These are the functions I have to handle the changes
handleCheckboxChange =(id) =>{
var data;
const selected = (e => e.FlightID = id);
this.handleAddToCart(id);
};
handleAddToCart(flight) {
const cartItem = this.state.cart.find(x => x.id === flight.id);
this.setState({cart: [...this.state.cart, flight]})
}
handleClick(flight) {
this.handleAddToCart(flight)
}
If anyone is able to help it would be greatly appreciated.

react.js antd modal wrong behaviour

So I have this big messy component, I will try to slim it down, however keep most of it since I am unsure at this point what could be cause.
The issue is, that the game works as expected. When it is time for the modal to render, it appears at the bottom left of the page, with no styling floating left. The functionality however works as expected, the buttons work and it displays the raw content.
import { Modal } from 'antd';
//rest of imports
const initialState = {
visible: false,
streak: 0,
score: 0,
turn: 0,
previousPicks: [],
result: { result: "", player: "", computer: "" }
};
class Game extends React.Component {
constructor(props) {
super(props);
this.turnLimit = 10;
this.state = initialState;
}
componentWillUnmount() {
this.setState(initialState)
}
updateScore = () => {
//handles score
}
updatePreviousPicks = () => {
//update game data
}
onClickHandler = async (choice) => {
//fetching data from backend
self.showModal();
}
getAIResult = () => {
//
}
showModal = () => {
if (this.state.turn === 10) {
this.setState({
visible: true,
});
}
}
handleOk = () => {
this.setState(initialState)
}
handleCancel = () => {
this.setState(initialState)
}
render() {
return (
<div>
<div>
<Modal
title="Basic Modal"
centered={true}
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}></Modal>
</div>
<div className="container">
<div id="rockDiv" className={`choice`} onClick={() => this.onClickHandler("rock")}>
<Choices choice="rock"></Choices>
</div>
<div id="paperDiv" className={`choice`} onClick={() => this.onClickHandler("paper")}>
<Choices choice="paper"></Choices>
</div>
<div id="scissorsDiv" className={`choice`} onClick={() => this.onClickHandler("scissors")}>
<Choices choice="scissors"></Choices>
</div>
<Score score={this.state.score} bonus={this.state.streak} turn={this.state.turn} />
<div id="PlayerResult" className={this.state.result.result} >
{this.state.turn >= 1 ? <p>You</p> : <p></p>}
<Answer choice={`${this.state.result.player}`} />
</div>
<div id="AIResult" className={this.getAIResult()} >
{this.state.turn >= 1 ? <p>AI</p> : <p></p>}
<Answer choice={`${this.state.result.computer}`} />
</div>
</div>
</div>
)
}
}
export default Game
I have tried removing all CSS from the component, and still the modal does not show with the default antd design?
As I understand that current style you have doesn't like example of Antd.
Missing is you didn't import styles of Antd like this.
import { Modal, Button } from "antd";
import "antd/dist/antd.css";
Just need import style you will have what you need.
You can check my example here https://codesandbox.io/embed/8lr93mw8yj
<Modal
title="Basic Modal"
centered="true"
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}></Modal>
You do not need to wrap the "true" in brackets here as you are not calling a variable.

Categories

Resources