I have a modify-button that displays a modal component according to the value of the state property "modalVisible", in other terms the modify-button trigger an event handler which update the state property but since setState is asynchronous, the modal doesn't display properly (sometimes it shows sometimes not)
Is there an alternative to show the modal immediately after clicking modify button in react ?
here is my code i have 4 Components :
The first is Todo component which is used to display the 2 other components: DisplayTasks component (to do list) and the DisplayCompletedTasks (tasks completed),
The fourth is Modal component (just an input text to change the name of the task) which is displayed when clicking on the button modify-button
First component file TaskManagements.js
import React from 'react'
import {DisplayTasks} from './DisplayTasks'
import DisplayCompletedTasks from './DisplayCompletedTasks'
export class Todo extends React.Component{
constructor(props){
super(props);
this.state={
task: '',
tasks: [],
completedTasks: [],
inputVisible: false,
completedVisible: false,
modalVisible: false,
buttonClicked: ''
};
}
toggleInputDisplay = ()=>{
this.setState(state=>({inputVisible: !state.inputVisible}));
}
handleChange = (event)=>{
// Handle input checkboxes that handle completed tasks (the alternative is to use event.target.type==="checkboxes")
if(event.target.name==="choosed"){
//document.querySelector("input[value='" + event.target.value + "']").style.background-color = ""
let arr = this.state.tasks;
arr[event.target.value].checked = !arr[event.target.value].checked;
this.setState({tasks: arr});
}
// Handle the text input storing the text within the task state property
else if(event.target.type==="text"){
this.setState({task: event.target.value});
}
}
addTask = (event)=>{
const arr = this.state.tasks;
arr.push({task: this.state.task, checked: false});
this.setState(state=>({tasks: arr, task: ''}));
}
removeTask = (event)=>{
const arr = this.state.tasks;
arr.splice(event.target.id,1);
this.setState(state=>({tasks: arr}));
}
modifyTask = (event)=>{
this.setState({modalVisible: true});
}
handleParam = (event)=>{
const name = event.target.name;
let arr = this.state.tasks;
arr.forEach(task=>(task.checked = false));
this.setState(state=>({completedVisible: !state.completedVisible, buttonClicked: name,
tasks: arr}));
console.log(this.state.tasks);
}
handleChoosedTasks = (event)=>{
//const inputVar = document.querySelectorAll("[value][name='completed']:checked");
this.setState(state=>({tasks: state.tasks.filter(task=>(!task.checked)), completedVisible: false}));
if(this.state.buttonClicked === 'complete'){
const completedTasks = this.state.tasks.filter(task=>(task.checked));
this.setState(state=>({completedTasks: state.completedTasks.concat(completedTasks)}));
console.log('completed:' + this.state.completedTasks);
}
}
render(){
console.log(this.state.tasks);
return(
<div className="h-100">
<button className="mt-4 btn btn-outline-primary" onClick={this.toggleInputDisplay}>Add Task</button>
<div className="mt-5 ">{!this.state.inputVisible ? '' : (
<div className="mb-4">
<input className="mr-1"type="text" value={this.state.task} onChange={this.handleChange}/>
<button className="btn btn-outline-secondary mr-1" onClick={this.addTask}>Add</button>
<button className="btn btn-outline-secondary" onClick={this.toggleInputDisplay}>Cancel</button>
</div>
)
}
<div className="row p-0 col-6 mx-auto ">
<span style={{"paddingLeft": "14%"}} className=" mb-0 ml-0 col-10 ">Tasks</span>
<button id="complete" name="complete" style={{"fontSize": "14px"}} className="btn btn-success col p-0" onClick={this.handleParam}>
complete</button>
<button id="remove" name="remove" style={{"fontSize": "14px","marginLeft":"5px"}} className="btn btn-danger col p-0" onClick={this.handleParam}>
remove</button>
</div>
<DisplayTasks tasks={this.state.tasks} removeTask={this.removeTask}
completedVisible={this.state.completedVisible} handleChange={this.handleChange}
handleChoosedTasks={this.handleChoosedTasks} modifyTask={this.modifyTask} modalVisible={this.state.modalVisible}/>
<span className=" mb-0 ">Completed</span>
<DisplayCompletedTasks completedTasks={this.state.completedTasks}/>
</div>
</div>
);
}
}
second file DisplayTasks.js
import React from 'react'
import ModifiedModal from './ModifiedModal.js'
import './DisplayTasks.css'
export class DisplayTasks extends React.Component{
render(){
return(
<div id="tasks" style={{"height": "40vh"}} className="mt-2 mb-5 col-6 border border-primary mx-auto ">
{!this.props.modalVisible? '' : <ModifiedModal />}
<div style={{"height": "87%"}} className=" col-12 overflow-auto">{!this.props.tasks.length ? '' : this.props.tasks.map((task,index)=>
(
<div key={`task-${index}`} className="mt-3 mr-0 d-flex p-0 w-100 border">
<div id="parent-task" style={!task.checked ? {...this.style}: {...this.style,"backgroundColor":"yellow"}} className="col-12 ml-0 p-0 d-flex">{!this.props.completedVisible ? ''
: (<label id="c-customized" className="border">
<input name="choosed" type="checkbox" value={index}
onChange={this.props.handleChange}/>
<svg width="30" height="30">
<g>
<circle className="c-b" cx="15" cy="15" r="14" stroke="magenta"/>
<polyline className="c-m" points="6,14 12,20 23,9"/>
</g>
</svg>
</label>)}
<strong className="ml-0 col-11 d-inline-block align-self-center">
{task.task}
</strong>
<button id="modify-button" className="btn btn-primary btn-circle mr-1"><i value={index} className="fas fa-pencil-alt"
onClick={this.props.modifyTask}></i></button>
</div>
</div>
)
)
}
</div>
{!this.props.completedVisible ? ''
: <button id="choosed-confirmed" className="d-flex btn btn-success" onClick={this.props.handleChoosedTasks}>
<span className="mx-auto align-self-center">Ok</span></button>}
</div>
)
}
}
The fourth is the Modal
import React from 'react'
export default function ModifiedModal(props){
console.log("modifiedModal");
return <div className="Modal d-flex ">
<label>
<button id="x-button"></button>
<span>Modify the Task</span>
<input type="text" />
</label>
</div>
}
Use callback of setState like :
this.setState({ variable : updatedValue }, () => {
after update works here...
}
);
Related
import React, { useEffect, useState } from "react";
import { useNavigate } from 'react-router-dom';
import PropTypes from "prop-types";
import { withTranslation } from "react-i18next";
import { FaCheck, FaTimes } from "react-icons/fa";
import { CircularProgressbarWithChildren, buildStyles } from "react-circular-progressbar";
import { easeQuadInOut } from "d3-ease";
import AnimatedProgressProvider from "../../../utils/AnimatedProgressProvider";
import "react-circular-progressbar/dist/styles.css";
import { useSelector } from "react-redux";
import { sysConfigdata } from "../../../store/reducers/settingsSlice";
function ShowScore({ t, score, totalQuestions, onPlayAgainClick, onReviewAnswersClick, onNextLevelClick, coins, quizScore, currentLevel, maxLevel, reviewAnswer, playAgain, nextlevel }) {
const [perValue, setPerValue] = useState(0);
const navigate = useNavigate();
const percentage = (score * 100) / totalQuestions;
// store data get
const userData = useSelector((state) => state.User);
const systemconfig = useSelector(sysConfigdata);
const goToHome = () => {
navigate("/");
};
const goBack = () => {
navigate("Quizplay");
};
// server image error
const imgError = (e) => {
e.target.src = "/images/user.webp"
}
return (
<React.Fragment>
<div className="score-section text-center bold">
{percentage >= Number(systemconfig.maximum_coins_winning_percentage) ? (
<>
<h4 className="winlos">
<b>{t("Winner")}</b>
</h4>
<h5 >{t("Congratulations")}</h5>
</>
) : (
<>
<h4 className="winlos">
<b>{t("Defeat")}</b>
</h4>
<h5 >{t("Better Luck Next Time")}</h5>
</>
)}
</div>
<div className="my-4 row d-flex align-items-center">
<div className="col-md-5 col-4 coin_score_screen ">
<h4 className=" score-circle-title">{t("Coins")}</h4>
<div className="score-circle ml-auto">
<CircularProgressbarWithChildren value={0} strokeWidth={5} styles={buildStyles({trailColor: '#f8c7d8'})}>
<h4 className=" mb-0">{coins ? coins : "0"}</h4>
</CircularProgressbarWithChildren>
</div>
</div>
<div className="col-md-2 col-4 coin_score_screen score-section text-center bold">
<div className="d-inline-block">
<AnimatedProgressProvider valueStart={0} valueEnd={percentage} duration={0.2} easingFunction={easeQuadInOut}>
{(value) => {
const roundedValue = Math.round(value);
setPerValue(roundedValue);
return (
<CircularProgressbarWithChildren
value={value}
strokeWidth={5}
styles={buildStyles({
pathTransition: "none",
textColor: "#ef5488",
trailColor: '#f5f5f8',
pathColor: percentage >= Number(systemconfig.maximum_coins_winning_percentage) ? "#15ad5a" : "#ef5488",
})}
>
<img src={userData.data && userData.data.profile ? userData.data.profile : process.env.PUBLIC_URL + "/images/user.webp"} alt="user" className="showscore-userprofile" onError={imgError}/>
</CircularProgressbarWithChildren>
);
}}
</AnimatedProgressProvider>
</div>
</div>
<div className="col-md-5 col-4 coin_score_screen ">
<h4 className=" score-circle-title">{t("Score")}</h4>
<div className="score-circle">
<CircularProgressbarWithChildren value={0} strokeWidth={5} styles={buildStyles({trailColor: '#f8c7d8'})}>
<h4 className=" mb-0">{quizScore ? quizScore : "0"}</h4>
</CircularProgressbarWithChildren>
</div>
</div>
</div>
<div className="my-4 align-items-center d-flex">
<div className="col-4 col-md-5 right_wrong_screen text-end" title={t("Incorrect Answers")}>
<h1 className="score-badge bg-danger mb-0">
{/* {console.log("score",score,"totalquestions",totalQuestions)} */}
<FaTimes /> {totalQuestions - score + " / " + totalQuestions}
</h1>
</div>
<div className="col-4 col-md-2 right_wrong_screen text-center percent_value">
<h1 className="winlos percentage">{perValue}%</h1>
</div>
<div className="col-4 col-md-5 right_wrong_screen text-start" title={t("Correct Answers")}>
<div className="score-badge bg-success">
<FaCheck />
<span> {score + " / " + totalQuestions}</span>
</div>
</div>
</div>
<div className="dashoptions row text-center">
{percentage >= Number(systemconfig.maximum_coins_winning_percentage) && maxLevel !== String(currentLevel) ? (
nextlevel ? (
<div className="fifty__fifty col-12 col-sm-6 col-md-2 custom-dash">
<button className="btn btn-primary" onClick={onNextLevelClick}>
{t("Next Level")}
</button>
</div>
) : (
""
)
) : playAgain ? (
<div className="fifty__fifty col-12 col-sm-6 col-md-2 custom-dash">
<button className="btn btn-primary" onClick={onPlayAgainClick}>
{t("Play Again")}
</button>
</div>
) : (
""
)}
{reviewAnswer ? (
<div className="audience__poll col-12 col-sm-6 col-md-2 custom-dash">
<button className="btn btn-primary" onClick={onReviewAnswersClick}>
{t("Review Answers")}
</button>
</div>
) : (
""
)}
<div className="resettimer col-12 col-sm-6 col-md-2 custom-dash">
<button className="btn btn-primary" onClick={goBack}>
{t("Back")}
</button>
</div>
<div className="skip__questions col-12 col-sm-6 col-md-2 custom-dash">
<button className="btn btn-primary" onClick={goToHome}>
{t("Home")}
</button>
</div>
</div>
</React.Fragment>
);
}
ShowScore.propTypes = {
score: PropTypes.number.isRequired,
totalQuestions: PropTypes.number.isRequired,
// coins: PropTypes.number.isRequired,
quizScore: PropTypes.number.isRequired,
// onPlayAgainClick: PropTypes.func.isRequired,
// onReviewAnswersClick: PropTypes.func.isRequired,
// onNextLevelClick: PropTypes.func.isRequired,
};
export default withTranslation()(ShowScore);
when i complete the quiz game and at end component call showscore.jsx and its running perfectly but in console throws error with badstate with setstate i cant understand please provide optimum solution to remove or solve this error if you contact me with email or get file of code i will send you just ping me on email sumi.mayani#gmail.com
I have tried everything but no solution. Please anybody help.
my partial code:
socialLogin.js
const SocialLogin = () => {
const [signInWithGoogle, googleUser, googleLoading, googleError] =
useSignInWithGoogle(auth);
return (
<div>
<div className=" d-flex justify-content-evenly ">
<button
onClick={() => signInWithGoogle()}
type="submit"
className="btn btn-outline-primary"
>
<img className="px-2" src={google} alt="" />
Sign in with Google
</button>
</div>
</div>
);
};
export default SocialLogin;
I implemented a Card component and basically generating a bunch of cards on some input data. I binded a setter function on button click on every card which basically expands and collapse it. Even after putting unique keys to the div is sort of triggering all the cards to open at once.
Here is the code piece:
import React, { useState } from 'react';
import PrettyPrintJson from './PrettyPrintJson';
import './Card.scss';
import '../App.scss';
const Card = (props) => {
const { data } = props;
const [collapse, toggleCollapse] = useState(true);
return (<div className="card-group">
{data.map((obj, idx)=>{
return <div className="card" key={`${idx}_${obj?.lastModifiedOn}`}>
<div className="card-header">
<h4 className="card-title">{`fId: ${obj?.fId}`}</h4>
<h6 className="card-title">{`name: ${obj?.name}`}</h6>
<h6 className="card-title">{`status: ${obj?.status}`}</h6>
<div className="heading-elements">
<button className="btn btn-primary" onClick={() => toggleCollapse(!collapse)}>Show Json</button>
</div>
</div>
<div className={`card-content ${!collapse ? 'collapse show' : 'collapsing'}`}>
<div className="card-body">
<div className="row">
<PrettyPrintJson data={ obj } />
</div>
</div>
</div>
</div>
})}
</div>
);
}
export default Card;
Create a component that manages it's own state and render that component.
const CardItem = ({ obj }) => {
const [collapse, toggleCollapse] = useState(true);
return (<div className="card">
<div className="card-header">
<h4 className="card-title">{`fId: ${obj?.fId}`}</h4>
<h6 className="card-title">{`name: ${obj?.name}`}</h6>
<h6 className="card-title">{`status: ${obj?.status}`}</h6>
<div className="heading-elements">
<button className="btn btn-primary" onClick={() => toggleCollapse(!collapse)}>Show Json</button>
</div>
</div>
<div className={`card-content ${!collapse ? 'collapse show' : 'collapsing'}`}>
<div className="card-body">
<div className="row">
<PrettyPrintJson data={ obj } />
</div>
</div>
</div>
</div>)
}
then render it like
{data.map((obj, idx)=> (<CardItem obj={obj} key={idx} />))}
I think you can declare a state which is a type of int. After then, you can use the if-statement of index(idx) and state.
Like this:
const [collapsedCardNumbers, toggleCollapseCard] = useState([]);
const addCardNumber = (idx, prevState) => {
const arr_cardNum = prevState
!arr_cardNum .includes(idx) && arr_cardNum .push(idx)
return arr_cardNum
}
...
{data.map((obj, idx)=>{
return <div className="card" key={`${idx}_${obj?.lastModifiedOn}`}>
<div className="card-header">
<h4 className="card-title">{`fId: ${obj?.fId}`}</h4>
<h6 className="card-title">{`name: ${obj?.name}`}</h6>
<h6 className="card-title">{`status: ${obj?.status}`}</h6>
<div className="heading-elements">
<button className="btn btn-primary" onClick={() => toggleCollapseCard(prevState => addCardNumber(idx, prevState))}>Show Json</button>
</div>
</div>
<div className={`card-content ${collapsedCardNumbers.includes(idx) ? 'collapse show' : 'collapsing'}`}>
<div className="card-body">
<div className="row">
<PrettyPrintJson data={ obj } />
</div>
</div>
</div>
</div>
})}
I am displaying two divisions corresponding, to two button's onClick event:
class Home extends React.Component {
constructor() {
super();
this.state = {
isShowaMale: false
};
this.toggleShowMale = this.toggleShowMale.bind(this);
}
toggleShowMale(show) {
this.setState({ isShowaMale:show });
}
render() {
const { isShowaMale } = this.state;
return (
<div className="container py-5">
<div className="row">
<button className="btn col-6 bg-transparent col-12 col-sm-6" onClick={() => this.toggleShowMale(true)} >
<img className="humanbody profile" src={malebody} />
</button>
<button className="btn col-6 bg-transparent col-12 col-sm-6" onClick={() => this.toggleShowMale(false)} >
<img className="humanbody profile" src={femalebody} alt="" />
</button>
</div>
{/* Hidden div */}
<div className="row mx-auto">
{isShowaMale && (
<div className="mx-auto">
Hey man!
</div>
)}
{!isShowaMale && (
<div>
Hey woman!
</div>
)}
</div>
{/* Hidden div */}
</div>
)
}
}
export default Home;
But, can I just display one div and change just the word man and woman in the text Hey ____? And there is also a problem that, after reloading the web page, it always shows Hey woman due to isShowaMale: false being default state. How can I solve these?
Can I just display one div and change just the word man and woman in
the text Hey ____
<div className="row">
{`Hey ${isShowMan? " man" : "woman"}!`}
</div>
And there is also a problem that, after reloading the web page, it always shows Hey woman due to isShowaMale: false being the default
state.
You can think about localStorage
Due to Why are we disallowed to use HTML5 local storage on code snippets?
So you can test the live demo
constructor() {
super();
const isShow = window.localStorage.getItem("data");
this.state = { isShowMan: isShow === "false" || !isShow ? false : true };
}
toggleShowMan(isShow) {
window.localStorage.setItem("data", isShow);
this.setState({ isShowMan: isShow });
}
class Home extends React.Component {
constructor() {
super();
this.state = { isShowMan: true };
}
toggleShowMan(isShow) {
this.setState({ isShowMan: isShow });
}
render() {
const { isShowMan } = this.state;
return (
<div className="container py-5">
<div className="row">
<button
disabled={isShowMan}
className="btn col-6 bg-transparent col-12 col-sm-6"
onClick={() => this.toggleShowMan(true)}
>
malebody{" "}
</button>
<button
disabled={!isShowMan}
className="btn col-6 bg-transparent col-12 col-sm-6"
onClick={() => this.toggleShowMan(false)}
>
femalebody
</button>
</div>
<div className="row">
{`Hey ${isShowMan? " man" : "woman"}!`}
</div>
</div>
);
}
}
ReactDOM.render(<Home />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
[UPDATE] following further clarification in the comments, the issue can be handles in a way similar to this:
class Home extends React.Component {
constructor() {
super();
this.state = {
isShowaMale: false
};
this.toggleShowMale = this.toggleShowMale.bind(this);
}
toggleShowMale(show) {
this.setState({ isShowaMale:show });
}
render() {
const formProps = this.state.isShowMale
? { title: 'Mr', name: 'John', surname: 'Doe' }
: { title: 'Ms', name: 'Jane', surname: 'Doe' };
return (
<div className="container py-5">
<div className="row">
<button className="btn col-6 bg-transparent col-12 col-sm-6" onClick={()=> this.toggleShowMale(true)} >
<img className="humanbody profile" src={malebody} />
</button>
<button className="btn col-6 bg-transparent col-12 col-sm-6" onClick={()=> this.toggleShowMale(false)} >
<img className="humanbody profile" src={femalebody} alt="" />
</button>
</div>
{/* Hidden div */}
<div className="row mx-auto">
<div className="mx-auto">
<form>
<input type="text" id="title" name="title" placeholder={formProps.title} />
<input type="text" id="name" name="name" placeholder={formProps.title} />
<input type="text" id="surname" name="surname" placeholder={formProps.title} />
</form>
</div>
</div>
{/* Hidden div */}
</div>
)
}
}
export default Home;
Or the entire form can be placed into a separate function (or even a separate component).
[ORIGINAL ANSWER]
You simply replace
{/* Hidden div */}
<div className="row mx-auto">
{isShowaMale && (
<div className="mx-auto">
Hey man!
</div>
)}
{!isShowaMale && (
<div>
Hey woman!
</div>
)}
</div>
{/* Hidden div */}
with
{/* Hidden div */}
<div className="row mx-auto">
<div className="mx-auto">
Hey {isShowaMale ? 'man' : 'woman'}!
</div>
</div>
{/* Hidden div */}
Okay I have an issue which has stumped me for hours now and I cannot for the life of me see what the issue is.
This is happening because of renderGuestOptions being used as a component in renderGuestPrices. The odd thing is if I change it from being an arrow function to a normal function() {} then it works, but then I cannot access 'this' to update the state.
I'm only using React and ReactDOM and I'm not using any exports or as such.
Error Text:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
import React from 'react';
import ReactDOM from 'react-dom'
class TimeSlots extends React.Component {
constructor(props) {
super(props);
this.telephone = getCalendarWrapper().dataset.telephone;
// this.timeSlotButtons = React.createRef();
// this.monthPrevious = React.createRef();
// this.monthPreviousByYear = React.createRef();
// this.monthForward = React.createRef();
// this.monthForwardByYear = React.createRef();
this.state = {
currentDate: this.props.currentDate,
timesAvailable: this.props.timesAvailable,
guests: null,
guestsSelected: null,
timeSlotSelected: null,
bookingModal: {
show: false
},
}
console.log(this.props.roomSlug);
console.log(this.props.currentDate);
console.log(this.props.timesAvailable);
}
// -----------------
// -- RENDERS GUEST OPTIONS WHEN USER HAS CLICKED A TIME SLOT
// -----------------
renderGuestOptions = (props) => {
// renderGuestOptions(props) {
// const guestDataTest = props.guestData.guestData;
const guestData = props.guestData;
console.log(this);
if (guestData) {
return(
// onChange we update the guestSelected state, which will then be used in the ajax request if its added
<select className="form-control" onChange={(event) => console.log(event.target.value)}>
{/* <select className="form-control" onChange={(event) => this.setState({guestsSelected: event.target.value})}> */}
{Object.keys(guestData).map(function(key) {
return <option key={key} value={key}>{key} People - £{guestData[key]}</option>
})}
</select>
);
} else {
return <h2>Sorry no times are available</h2>;
}
}
renderGuestPrices = () => {
if (!this.state.timeSlotSelected && !this.state.guests) {
return <div></div>;
}
return(
<form className="timeslot row" onSubmit={this.formSubmitHandler}>
<div className="col-12 mb-3 text-center">
<span className="title title--h2">How Many Guests?</span>
</div>
<div className="col-12 mb-3 mb-md-4">
<this.renderGuestOptions guestData={this.state.guests} />
</div>
<div className="col-12 text-center mb-3 mb-md-4">
<div className="room-calendar__timeslots__help">
</i> {this.telephone}
</div>
</div>
<div className="col-12">
<div className="d-block px-4">
<button className="btn d-block w-100 mb-3" type="submit">Add To Basket</button>
{/* <span className="btn d-block mb-3" onClick={() => this.addToBasketHandler()}>Add To Basket</span> */}
<button className="btn d-block w-100" type="submit">Book and Pay</button>
</div>
{/* <span className="btn">Book and Pay</span> */}
</div>
<div className="col-12">
</div>
<div className="room-calendar__timeslots__please-note col-12 text-center mt-4">
<p className="text-uppercase text-">Please note - adding to basket will redirect you to the locations page</p>
</div>
</form>
);
}
}
try to do something like this:
import ReactDOM from 'react-dom';
export default class TimeSlots extends React.Component {
constructor(props) {
super(props);
this.telephone = getCalendarWrapper().dataset.telephone;
// this.timeSlotButtons = React.createRef();
// this.monthPrevious = React.createRef();
// this.monthPreviousByYear = React.createRef();
// this.monthForward = React.createRef();
// this.monthForwardByYear = React.createRef();
this.state = {
currentDate: this.props.currentDate,
timesAvailable: this.props.timesAvailable,
guests: null,
guestsSelected: null,
timeSlotSelected: null,
bookingModal: {
show: false
}
};
console.log(this.props.roomSlug);
console.log(this.props.currentDate);
console.log(this.props.timesAvailable);
}
// -----------------
// -- RENDERS GUEST OPTIONS WHEN USER HAS CLICKED A TIME SLOT
// -----------------
renderGuestOptions() {
// renderGuestOptions(props) {
// const guestDataTest = props.guestData.guestData;
const guestData = this.props.guestData;
console.log(this);
if (guestData) {
return (
// onChange we update the guestSelected state, which will then be used in the ajax request if its added
<select
className="form-control"
onChange={event => console.log(event.target.value)}
>
{/* <select className="form-control" onChange={(event) => this.setState({guestsSelected: event.target.value})}> */}
{Object.keys(guestData).map(function(key) {
return (
<option key={key} value={key}>
{key} People - £{guestData[key]}
</option>
);
})}
</select>
);
} else {
return <h2>Sorry no times are available</h2>;
}
};
renderGuestPrices() {
if (!this.state.timeSlotSelected && !this.state.guests) {
return <div></div>;
}
return (
<form className="timeslot row" onSubmit={this.formSubmitHandler}>
<div className="col-12 mb-3 text-center">
<span className="title title--h2">How Many Guests?</span>
</div>
<div className="col-12 mb-3 mb-md-4">
<renderGuestOptions guestData={this.state.guests} />
</div>
<div className="col-12 text-center mb-3 mb-md-4">
<div className="room-calendar__timeslots__help">
<a href={'tel:' + this.telephone.replace(/ /g, '')}>
<i className="fa fa-phone"></i> {this.telephone}
</a>
</div>
</div>
<div className="col-12">
<div className="d-block px-4">
<button className="btn d-block w-100 mb-3" type="submit">
Add To Basket
</button>
{/* <span className="btn d-block mb-3" onClick={() => this.addToBasketHandler()}>Add To Basket</span> */}
<button className="btn d-block w-100" type="submit">
Book and Pay
</button>
</div>
{/* <span className="btn">Book and Pay</span> */}
</div>
<div className="col-12"></div>
<div className="room-calendar__timeslots__please-note col-12 text-center mt-4">
<p className="text-uppercase text-">
Please note - adding to basket will redirect you to the locations
page
</p>
</div>
</form>
);
};
render() {
return <renderGuestPrices />;
}
}