Return NaN - reactjs - reactjs

Good evening, have a question. I am starting to use react making a project with sponacular api. I have this code:
import Container from 'react-bootstrap/Container';
import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';
import Row from 'react-bootstrap/Row';
import ListGroup from 'react-bootstrap/ListGroup';
import { useContext } from 'react';
import { CartContext } from '../../CartContex/CartContext';
import "./CartOrden.css";
const CartOrden =()=>{
const {pedidoVegano, pedidoNoVegano, removeItem } = useContext(CartContext);
let totalPrecio = 0;
let tiempoEspera = 0;
let healthScore = 0;
const sumarTotal =(i)=>{
totalPrecio += i.pricePerServing;
console.log(totalPrecio)
}
const calculoEspera =(i)=>{
tiempoEspera += parseInt(i.readyInMinutes);
console.log(tiempoEspera)
}
const totalHealth = (i)=>{
healthScore += i.healthScore;
console.log(healthScore)
}
return (
<Container>
<div>
<h2>Vegan Menu</h2>
</div>
<Row className='m-3'>
{pedidoVegano.map((i=>{
sumarTotal(i.item)
calculoEspera(i.item)
totalHealth(i.item)
return(
<Card className='card-first' style={{ width: '18rem' }}>
<Card.Img className='card-img' variant="top" src={i.item.image} />
<Card.Body>
<Card.Title className='card-title'>{i.item.title}</Card.Title>
<div className='contain-value'>
<p className='text'><i className="fa-solid fa-dollar-sign"></i> {i.item.pricePerServing}</p>
<p className='text'><i className="fa-solid fa-heart"></i> {i.item.healthScore}</p>
<p className='text'><i class="fa-solid fa-clock"></i> {i.item.readyInMinutes}</p>
</div>
<div>
<Button onClick={()=> removeItem(i.item)} variant="danger"><i class="fa-solid fa-trash"></i> Delete</Button>
</div>
</Card.Body>
</Card>
)
}))}
</Row>
<div>
<h2>Vegan't Menu</h2>
</div>
<Row className='m-3'>
{pedidoNoVegano.map((i=>{
sumarTotal(i.item)
calculoEspera(i.item)
totalHealth(i.item)
return(
<Card className='card-first' style={{ width: '18rem' }}>
<Card.Img className='card-img' variant="top" src={i.item.image} />
<Card.Body>
<Card.Title>{i.item.title}</Card.Title>
<div className='contain-value'>
<p className='text'><i className="fa-solid fa-dollar-sign"></i> {i.item.pricePerServing}</p>
<p className='text'><i className="fa-solid fa-heart"></i> {i.item.healthScore}</p>
<p className='text'><i class="fa-solid fa-clock"></i> {i.item.readyInMinutes}</p>
</div>
<div>
<Button onClick={()=> removeItem(i.item)} variant="danger"><i class="fa-solid fa-trash"></i> Delete</Button>
</div>
</Card.Body>
</Card>
)
}))}
</Row>
<Row className='m-3'>
<Card>
<Card.Header as="h5">Current Menu</Card.Header>
<Card.Body>
<Card.Title>Total price: {totalPrecio}</Card.Title>
<Card.Title>Total health score: {healthScore} </Card.Title>
<Card.Title>Total preparation time: {tiempoEspera} minutes </Card.Title>
</Card.Body>
</Card>
</Row>
</Container>
)
}
export default CartOrden;
I wanted to unstructure the previous code, to make it more complex and work with components, as it should.
import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';
import { useContext } from 'react';
import { CartContext } from '../../CartContex/CartContext';
import "./CartOrden.css";
const CartOrden =({i})=>{
const { removeItem } = useContext(CartContext);
return(
<Card className='card-first' style={{ width: '18rem' }}>
<Card.Img className='card-img' variant="top" src={i.item.image} />
<Card.Body>
<Card.Title className='card-title'>{i.item.title}</Card.Title>
<div className='contain-value'>
<p className='text'><i className="fa-solid fa-dollar-sign"></i> {i.item.pricePerServing}</p>
<p className='text'><i className="fa-solid fa-heart"></i> {i.item.healthScore}</p>
<p className='text'><i class="fa-solid fa-clock"></i> {i.item.readyInMinutes}</p>
</div>
<div>
<Button onClick={()=> removeItem(i.item)} variant="danger"><i class="fa-solid fa-trash"></i> Delete</Button>
</div>
</Card.Body>
</Card>
)
}
export default CartOrden;
import Container from 'react-bootstrap/Container';
import Card from 'react-bootstrap/Card';
import Row from 'react-bootstrap/Row';
import { useContext } from 'react';
import { CartContext } from '../../CartContex/CartContext';
import CartOrden from '../CartOrden/CartOrden';
const ResultOrden =()=>{
const {pedidoVegano, pedidoNoVegano, } = useContext(CartContext);
let totalPrecio = 0;
let tiempoEspera = 0;
let healthScore = 0;
const sumarTotal =(i)=>{
totalPrecio += i.pricePerServing;
console.log(totalPrecio)
}
const calculoEspera =(i)=>{
tiempoEspera += parseInt(i.readyInMinutes);
console.log(tiempoEspera)
}
const totalHealth = (i)=>{
healthScore += i.healthScore;
console.log(healthScore)
}
return (
<Container>
<div>
<h2>Vegan Menu</h2>
</div>
<Row className='m-3'>
{pedidoVegano.map((i=>{
sumarTotal(i)
calculoEspera(i)
totalHealth(i)
return(
<CartOrden i={i} key={i.pricePerServing}/>
)
}))}
</Row>
<div>
<h2>Vegan't Menu</h2>
</div>
<Row className='m-3'>
{pedidoNoVegano.map((i=>{
sumarTotal(i)
calculoEspera(i)
totalHealth(i)
return(
<CartOrden i={i} key={i.id}/>
)
}))}
</Row>
<Row className='m-3'>
<Card>
<Card.Header as="h5">Current Menu</Card.Header>
<Card.Body>
<Card.Title>Total price: {totalPrecio}</Card.Title>
<Card.Title>Total health score: {healthScore} </Card.Title>
<Card.Title>Total preparation time: {tiempoEspera} minutes </Card.Title>
</Card.Body>
</Card>
</Row>
</Container>
)
}
export default ResultOrden;
I wanted to know why in the first case the code works but in the second within ResultOrden, the healthScore, tiempoEspera and totalPrice returns NaN.
example image
Sorry if the question is basic, I was trying to solve it and I couldn't. I'm probably missing something about communication between components but couldn't find it. If anyone can give me some advice, I'd appreciate it.

Related

Large base64 image produces "Maximum call stack size exceeded" in React

I am storing webpage content as a byte[] logo and an html body in database. When I click to load a specific category group, I get "Maximum call stack size exceeded" if the logo image is too large (in this case > 200kB). But if I store the same image as a base64 tagged image inside the html body, it doesn't fail. I've searched and searched but I cant find an explanation for this behavior. I searched for other answers. I changed the way I store the image. I tested different sizes. I expect the logo to load async regardless of size. I'm newer to React; any guidance would be appreciated.
Here is the MemberBenefit object:
export default interface MemberBenefit {
Id: string;
Name: string;
CategoryId: string;
Logo: ImageFile;
Detail: string;
}
export interface MemberBenefitCategory{
id: string;
Name: string;
ParentId: string;
}
export interface ImageFile{
data: number[];
contentType: string;
fileName: string;
}
The code where the logo and body are rendered is here:
<Accordion.Collapse eventKey={benefit.Id.toString()}>
<Card.Body>
{benefit.Logo &&
<>
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
</>
}
<section
className="not-found-controller"
dangerouslySetInnerHTML={{ __html: benefit.Detail }}
/>
</Card.Body>
</Accordion.Collapse>
Here is the whole TSX file for reference. I'm sure I am being very inefficient in many places, so I appreciate all the constructive feedback.
import React, { useEffect, useState } from "react"
import {Container, Row, Col, Breadcrumb, Button, Card, Accordion} from "react-bootstrap"
import {Redirect, Link} from "react-router-dom"
import ClientApi from "../../api/ClientApi"
import {ContainsAuthExpiredError} from "../../models/ErrorDetail"
import BenefitGroupPicker from "../../views/benefits/BenefitGroupPicker"
import PageHeading from "../../views/PageHeading"
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { library } from '#fortawesome/fontawesome-svg-core'
import MemberBenefit, { MemberBenefitCategory } from "../../models/MemberBenefit"
import { faBriefcase, faCar, faCarrot, faCircle, faDollarSign, faFaceGrinWide, faHeartPulse, faHouseChimney, faPlaneUp, faSailboat, faSquare, faWrench } from "#fortawesome/free-solid-svg-icons"
const Index: React.FC = () => {
const {errors, payload} = ClientApi.Account.UseAccountOverview()
const accountOverview = payload
const redirectToDisabled = accountOverview?.MembershipSummary.IsDelinquent ?? false
const [categories, set_categories] = useState<MemberBenefitCategory[] >([]);
const [selectedParentCategoryIndex, set_selectedParentCategoryIndex] = useState<number | null>(null);
const [loadedMemberBenefits, set_loadedMemberBenefits] = useState<MemberBenefit[] | null>(null);
useEffect(() => {
let mounted = true
const fetchData = async () => {
var [_getCategories, _error] = await ClientApi.Benefits.GetMemberBenefitCategories();
if (mounted) {
if (_error.length > 0) {
//set_benefitsLoadingErrors(allErrors)
} else {
set_categories(_getCategories ?? [])
}
}
}
fetchData()
return () => {
mounted = false
}
}, [])
const LoadParent = async (parentCategoryId:string) =>{
var [_getMemberBenefits, _error] = await ClientApi.Benefits.GetMemberBenefits(parentCategoryId ?? 0);
set_loadedMemberBenefits(_getMemberBenefits)
set_selectedParentCategoryIndex(categories.findIndex(category=> category.id == parentCategoryId))
}
// maybe fold these into 1 redirection checker function?
if (ContainsAuthExpiredError(errors)) {
return <Redirect to='/login' />
}
if (redirectToDisabled) {
return <Redirect to='/memberBenefits/Disabled' />
}
if (accountOverview && accountOverview.MembershipSummary.IsTerminated) {
return <Redirect to='/myMembership/PayDues' />
}
return (
<div className='component_BenefitsIndex'>
<PageHeading>
Member <b>Benefits</b>
</PageHeading>
<Container className='pageContent'>
<div className="d-lg-none d-xl-none ">
{selectedParentCategoryIndex == null &&
<>
<div id="benefitsPicker" style={{marginTop:"15px"}}>
<Row style={{textAlign:"center",lineHeight:"48px"}}>
<Col>
<button onClick={() => LoadParent("5")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}}>
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faWrench} size='2x'/>
</span>
<div>Equipment</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("1")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white", fontSize:"30px", top:"-15px", left:"-15px"}} icon={faSailboat}/>
<FontAwesomeIcon style={{color:"#FF671E", fontSize:"25px",top:"10px", left:"10px"}} icon={faSquare} />
<FontAwesomeIcon style={{color:"#FF671E", fontSize:"35px", top:"10px", left:"10px"}} icon={faCar} />
<FontAwesomeIcon style={{color:"#FF671E", width:"100px", height:"10px", top:"15px", left:"-7px"}} icon={faSquare} />
<FontAwesomeIcon style={{color:"white", fontSize:"30px", top:"10px", left:"10px"}} icon={faCar} />
</span>
<div>Auto/Boat</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("2")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faPlaneUp} size='2x'/>
</span>
<div>Travel</div>
</button>
</Col>
</Row>
<Row style={{textAlign:"center",lineHeight:"48px"}}>
<Col>
<button onClick={() => LoadParent("6")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faDollarSign} size='2x'/>
</span>
<div>Financial</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("3")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faHouseChimney} size='2x'/>
</span>
<div>Home/Farm</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("7")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faHeartPulse} size='2x'/>
</span>
<div>Health</div>
</button>
</Col>
</Row>
<Row style={{textAlign:"center",lineHeight:"48px"}}>
<Col>
<button onClick={() => LoadParent("4")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faFaceGrinWide} size='2x'/>
</span>
<div style={{marginTop: "11px",lineHeight: "25px"}}>Attractions/<br/>Sports</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("8")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faBriefcase} size='2x'/>
</span>
<div>Career</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("9")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faCarrot} size='2x'/>
</span>
<div>FAMA</div>
</button>
</Col>
</Row>
</div>
</>
}
{selectedParentCategoryIndex != null &&
<>
<button onClick={()=>set_selectedParentCategoryIndex(null)}>back</button>
<div className='blockNavContent'>
<h2>{categories[selectedParentCategoryIndex].Name}</h2>
{
categories.filter(category=>{return category.ParentId == categories[selectedParentCategoryIndex].id}).map(category=>
<Accordion key={category.id+"sub"}>
<Card>
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={category.id.toString()}>
{category.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={category.id.toString()}>
<Card.Body>
{
loadedMemberBenefits?.filter(benefit=>benefit.CategoryId == category.id.toString()).map(benefit=>
<Accordion key={benefit.Id +"subbenefit"}>
<Card >
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={benefit.Id.toString()}>
{benefit.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={benefit.Id.toString()}>
<Card.Body>
{benefit.Logo &&
<>
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
</>
}
<section
className="not-found-controller"
dangerouslySetInnerHTML={{ __html: benefit.Detail }}
/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
{
loadedMemberBenefits?.filter(benefit=>benefit.CategoryId == categories[selectedParentCategoryIndex].id.toString()).map(benefit=>
<Accordion key={benefit.Id +"sub"}>
<Card >
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={benefit.Id.toString()}>
{benefit.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={benefit.Id.toString()}>
<Card.Body>
{benefit.Logo &&
<>
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
</>
}
<section
className="not-found-controller"
dangerouslySetInnerHTML={{ __html: benefit.Detail }}
/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
</div>
</>
}
</div>
<Row className="d-none d-lg-block">
<Col>
<div className="blockNavGrid">
<div className="blockNavsList">
{
categories.filter(category=>{return category.ParentId == ""}).map(category=>
<div key={category.id}>
<Button onClick={() => LoadParent(category.id)} >
{category.Name}
</Button>
</div>
)
}
</div>
{selectedParentCategoryIndex == null &&
<>
<div className='blockNavContent'>
<div style={{marginBottom: "48px"}}>
<img
src='https://apps.floridafarmbureau.com/_cdn/img/MembershipMeansMoreHeader.svg'
alt='Membership Means More'
/>
</div>
<p>
Membership with Florida Farm Bureau means that you are part of a
growing community of member families in Florida. Members, just
like you, advocate for agriculture and grow as better leaders in
our state through their membership. As a thank you for your
membership, you are provided with access to over 30 companies to
provide benefits and discounts.
</p>
<p>Click a section for more information. </p>
</div>
</>
}
{selectedParentCategoryIndex != null &&
<>
<div className='blockNavContent'>
<h2>{categories[selectedParentCategoryIndex].Name}</h2>
{
categories.filter(category=>{return category.ParentId == categories[selectedParentCategoryIndex].id}).map(category=>
<Accordion key={category.id+"sub"}>
<Card>
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={category.id.toString()}>
{category.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={category.id.toString()}>
<Card.Body>
{
loadedMemberBenefits?.filter(benefit=>benefit.CategoryId == category.id.toString()).map(benefit=>
<Accordion key={benefit.Id +"subbenefit"}>
<Card >
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={benefit.Id.toString()}>
{benefit.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={benefit.Id.toString()}>
<Card.Body>
{benefit.Logo &&
<>
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
</>
}
<section
className="not-found-controller"
dangerouslySetInnerHTML={{ __html: benefit.Detail }}
/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
{
loadedMemberBenefits?.filter(benefit=>benefit.CategoryId == categories[selectedParentCategoryIndex].id.toString()).map(benefit=>
<Accordion key={benefit.Id +"sub"}>
<Card >
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={benefit.Id.toString()}>
{benefit.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={benefit.Id.toString()}>
<Card.Body>
{benefit.Logo &&
<>
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
</>
}
<section
className="not-found-controller"
dangerouslySetInnerHTML={{ __html: benefit.Detail }}
/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
</div>
</>
}
</div>
</Col>
</Row>
</Container>
</div>
)
}
export default Index
Error Screen
Error Text:
RangeError: Maximum call stack size exceeded
(anonymous function)
C:/Source/Repos/Federation.Homestead/MyFfbfPortal/my-ffbf-portal/src/pages/benefits/Index.tsx:233
230 |
231 | {benefit.Logo &&
232 | <>
> 233 | <img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
| ^ 234 | </>
235 | }
236 | <section
Index
C:/Source/Repos/Federation.Homestead/MyFfbfPortal/my-ffbf-portal/src/pages/benefits/Index.tsx:175
172 |
173 | {
174 | categories.filter(category=>{return category.ParentId == categories[selectedParentCategoryIndex].id}).map(category=>
> 175 | <Accordion key={category.id+"sub"}>
| ^ 176 | <Card>
177 | <Card.Header>
178 | {/* This was Accordion.Toggle in old version */}
▶ 18 stack frames were collapsed.
LoadParent
C:/Source/Repos/Federation.Homestead/MyFfbfPortal/my-ffbf-portal/src/pages/benefits/Index.tsx:48
45 | const LoadParent = async (parentCategoryId:string) =>{
46 | var [_getMemberBenefits, _error] = await MyFfbfClientApi.Benefits.GetMemberBenefits(parentCategoryId ?? 0);
47 | set_loadedMemberBenefits(_getMemberBenefits)
> 48 | set_selectedParentCategoryIndex(categories.findIndex(category=> category.id == parentCategoryId))
| ^ 49 | }
50 |
51 | // maybe fold these into 1 redirection checker function?
I think the problem is this: String.fromCharCode.apply it gets invoked for each byte/number in benefit.Logo.data inline and at a certain size the call stack exceeds.
The apply() method calls the specified function with a given this
value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
But beware: by using apply this way, you run the risk of exceeding the
JavaScript engine's argument length limit. The consequences of
applying a function with too many arguments (that is, more than tens
of thousands of arguments) varies across engines. (The JavaScriptCore
engine has hard-coded argument limit of 65536.)
So internally it looks like this:
// `null` will be replaced with the global object
btoa(window.String.fromCharCode(benefit.Logo.data[0]) + window.String.fromCharCode(benefit.Logo.data[1]) + ...)
Maybe you can store the image as raw binary, like in Image() or ArrayBuffer() or similiar and call toString("base64") on that?
Pseudo code:
export interface ImageFile{
data: ArrayBuffer;
contentType: string;
fileName: string;
}
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + benefit.Logo.data.toString("base64") }>
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
https://developer.mozilla.org/en-US/docs/Web/API/Blob
https://developer.mozilla.org/en-US/docs/Glossary/Base64

How to implement React-Bootstrap?

I'm trying to implement React-Bootstrap to my application and somehow it does not render.
This is the code that I have tried:
import React from 'react';
import { CardGroup, Card, Button, Container, CardImg, ListGroup, ListGroupItem, Row, Col } from 'react-bootstrap';
export class MovieView extends React.Component {
render() {
const { movie, onBackClick } = this.props;
return (
<Container>
<Row>
<Col>
<CardGroup>
<Card>
<CardImg className="movie-view movie-poster" src={movie.ImagePath} />
<Card.Body>
<Card.Title className="movie-title value">{movie.Title}</Card.Title>
<Card.Text className="movie-description value">{movie.Description}</Card.Text>
</Card.Body>
<Card.Body>
<ListGroup>
<ListGroupItem className="movie-genre">{movie.Genre.Name}</ListGroupItem>
<ListGroupItem className="movie-director">{movie.Director.Name}</ListGroupItem>
</ListGroup>
<Button variant="Primary" onClick={() => { onBackClick(null); }}>
Back
</Button>
</Card.Body>
</Card>
</CardGroup>
</Col>
</Row>
</Container>
);
}
}
If not, try adding this line in your src/index.js or App.js file
import 'bootstrap/dist/css/bootstrap.min.css';
See this documentation

I've been stomped for a couple days now, why is this not returning anything?

the initialState/loggedState methods seem to not be working... nothing will return
Can anyone point out what I did wrong? I'm stomped literally about to call it a day
...
Also useState works (kinda) but whenever I update the page it reverts back to initialState
ps. StackOverflow should let us post no matter how much code we have
import React, {useEffect} from 'react'
import './Home.css'
import {Card, Figure} from 'react-bootstrap'
import Data from './Data'
import {useMoralis} from 'react-moralis'
function Today() {
const { user } = useMoralis();
const initialState = (
<div className='status'>
<p>Guest</p>
</div>
)
const loggedState = (
<div className='status'>
<p>#</p>
</div>
)
const value = useEffect(() => {
if (user ) {
return(loggedState)
} else {
return(initialState)
}})
const current = new Date();
const date = `${current.getDate()}/${current.getMonth()+1}/${current.getFullYear()}`;
return(
<div>
<div className='top'>
<Card style={{ width: '100%' }} >
<Card.Body>
<Card.Title><span className='card-titled'>Home</span></Card.Title>
<Card.Subtitle className="mb-2 text-muted">Dashboard</Card.Subtitle>
<Card.Text>
Date: {date}
</Card.Text>
</Card.Body>
<Card.Body className='bannerlogo'>
<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/0/05/Ethereum_logo_2014.svg/73px-Ethereum_logo_2014.svg.png' alt="Girl in a jacket" width="60" height="90" />
</Card.Body>
<Card.Body className='profilepic'>
<Figure>
<Figure.Image
width={60}
height={70}
alt="171x180"
src="https://3.bp.blogspot.com/-UI5bnoLTRAE/VuU18_s6bRI/AAAAAAAADGA/uafLtb4ICCEK8iO3NOh1C_Clh86GajUkw/s320/guest.png"
/>
<Figure.Caption>
{value}
</Figure.Caption>
</Figure>
</Card.Body>
</Card>
</div>
<Data/>
</div>
)
}
export default Today
No need to use useEffect. you have useMolaris is custom hook already
function Today() {
const { user } = useMoralis();
const InitialState = (
<div className='status'>
<p>Guest</p>
</div>
)
const LoggedState = (
<div className='status'>
<p>#</p>
</div>
)
const current = new Date();
const date = `${current.getDate()}/${current.getMonth()+1}/${current.getFullYear()}`;
//Put conditional rendering if there's no user in functional component
if(!user) return <InitialState />
return(
<div>
<div className='top'>
<Card style={{ width: '100%' }} >
<Card.Body>
<Card.Title><span className='card-titled'>Home</span></Card.Title>
<Card.Subtitle className="mb-2 text-muted">Dashboard</Card.Subtitle>
<Card.Text>
Date: {date}
</Card.Text>
</Card.Body>
<Card.Body className='bannerlogo'>
<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/0/05/Ethereum_logo_2014.svg/73px-Ethereum_logo_2014.svg.png' alt="Girl in a jacket" width="60" height="90" />
</Card.Body>
<Card.Body className='profilepic'>
<Figure>
<Figure.Image
width={60}
height={70}
alt="171x180"
src="https://3.bp.blogspot.com/-UI5bnoLTRAE/VuU18_s6bRI/AAAAAAAADGA/uafLtb4ICCEK8iO3NOh1C_Clh86GajUkw/s320/guest.png"
/>
<Figure.Caption>
{value}
</Figure.Caption>
</Figure>
</Card.Body>
</Card>
</div>
<Data/>
</div>
)
}
export default Today

react slick slider convert class component to functional component

i am using react slick...and using class component, now i just want to convert class component to functional component....because in these component i need to use another function component...it getting some problem....could any one help on this thing...below the class i have used (renderArrows =) this i thing is getting problem...
this is the link of code sand box : https://codesandbox.io/s/jovial-smoke-ndzhj
import React, {Component } from 'react';
import { Col, Row } from 'react-grid-system';
import { ButtonBase } from '#material-ui/core';
import ArrowBackIosIcon from '#material-ui/icons/ArrowBackIos';
import ArrowForwardIosIcon from '#material-ui/icons/ArrowForwardIos';
import Slider from "react-slick";
class Example extends Component {
renderArrows = () => {
return (
<div className="slider-arrow">
<ButtonBase
className="arrow-btn prev"
onClick={() => this.slider.slickPrev()}
>
<ArrowBackIosIcon />
</ButtonBase>
<ButtonBase
className="arrow-btn next"
onClick={() => this.slider.slickNext()}
>
<ArrowForwardIosIcon />
</ButtonBase>
</div>
);
};
render() {
return (
<div>
<Col xl={12} lg={12} md={12} sm={12} xs={12} className="desktop-slider">
<div className="education-level main-boxes boxex-bottom">
<Row className="row">
<Col xl={4} lg={4} md={4} sm={12} xs={12}>
<div className="index-box-head horizontal-box-head">
1. Education Level
</div>
</Col>
<Col xl={8} lg={8} md={8} sm={12} xs={12}>
<div style={{ position: "relative" }}>
{this.renderArrows()}
<Slider
ref={c => (this.slider = c)}
dots={false}
arrows={false}
centerMode={true}
slidesToShow={1}
infinite={false}>
<li>Home
</li>
<li>About Us
</li>
<li>Gallery
</li>
</Slider>
</div>
</Col>
</Row>
</div>
</Col>
</div>
);
}
}
export default Example;
This can be the best answer
I tried and made this work with you sample
Check please
https://codesandbox.io/s/infallible-turing-wgvrb?file=/src/App.js
import React, { useRef } from "react";
import { Col, Row } from "react-grid-system";
import { ButtonBase } from "#material-ui/core";
import ArrowBackIosIcon from "#material-ui/icons/ArrowBackIos";
import ArrowForwardIosIcon from "#material-ui/icons/ArrowForwardIos";
import Slider from "react-slick";
const Example = () => {
const customSlider = useRef();
const renderArrows = () => {
return (
<div className="slider-arrow">
<ButtonBase
className="arrow-btn prev"
onClick={() => customSlider.current.slickPrev()}
>
<ArrowBackIosIcon />
</ButtonBase>
<ButtonBase
className="arrow-btn next"
onClick={() => customSlider.current.slickNext()}
>
<ArrowForwardIosIcon />
</ButtonBase>
</div>
);
};
return (
<div>
<Col xl={12} lg={12} md={12} sm={12} xs={12} className="desktop-slider">
<div className="education-level main-boxes boxex-bottom">
<Row className="row">
<Col xl={4} lg={4} md={4} sm={12} xs={12}>
<div className="index-box-head horizontal-box-head">
1. Education Level
</div>
</Col>
<Col xl={8} lg={8} md={8} sm={12} xs={12}>
<div style={{ position: "relative" }}>
{renderArrows()}
<Slider
ref={slider => (customSlider.current = slider)}
dots={false}
arrows={false}
centerMode={true}
slidesToShow={1}
infinite={false}
>
<li>Home</li>
<li>About Us</li>
<li>Gallery</li>
</Slider>
</div>
</Col>
</Row>
</div>
</Col>
</div>
);
};
export default Example;
class component to functional component:
import React, { Component } from 'react'
import { Col, Row } from 'react-grid-system'
import { ButtonBase } from '#material-ui/core'
import ArrowBackIosIcon from '#material-ui/icons/ArrowBackIos'
import ArrowForwardIosIcon from '#material-ui/icons/ArrowForwardIos'
import Slider from 'react-slick'
const renderArrows = () => {
return (
<div className="slider-arrow">
<ButtonBase
className="arrow-btn prev"
onClick={() => this.slider.slickPrev()}
>
<ArrowBackIosIcon />
</ButtonBase>
<ButtonBase
className="arrow-btn next"
onClick={() => this.slider.slickNext()}
>
<ArrowForwardIosIcon />
</ButtonBase>
</div>
)
}
const Example = () => {
return (
<div>
<Col xl={12} lg={12} md={12} sm={12} xs={12} className="desktop-slider">
<div className="education-level main-boxes boxex-bottom">
<Row className="row">
<Col xl={4} lg={4} md={4} sm={12} xs={12}>
<div className="index-box-head horizontal-box-head">
1. Education Level
</div>
</Col>
<Col xl={8} lg={8} md={8} sm={12} xs={12}>
<div style={{ position: 'relative' }}>
{renderArrows()}
<Slider
ref={c => (this.slider = c)}
dots={false}
arrows={false}
centerMode={true}
slidesToShow={1}
infinite={false}
>
<li>Home</li>
<li>About Us</li>
<li>Gallery</li>
</Slider>
</div>
</Col>
</Row>
</div>
</Col>
</div>
)
}
export default Example
One more thing, I don't seem to get from where this.slider.slickNext() came from. I think it would be this.Slider.slickPrev().
If I'm right, then for functional component, change it to Slider.slickPrev()

horizontal align card using map function ReactJS

I'm trying to align horizontal card using grid with react-bootstrap and map function
I'm using redux to bring the Data through the props so I create a JSON to traverse it with a function Map
this is a fraction of my code
render() {
//const { tablaCliente } = this.state
//const { isLoading } = this.state
const { entity } = this.props;
return (
<div>
<Header></Header>
<div className="col-xs-4">
<a className="btn btn-primary" href="/newclient">Nuevo Cliente</a>
</div>
<br />
<center>
<Spinner animation="border" role="status">
<span className="sr-only">Loading...</span>
</Spinner>
</center>
<Container>
{entity && entity.getAllEntities && entity.getAllEntities.length > 0 && entity.getAllEntities.map((item, index) => {
return (
<CardGroup value={item}key={index}>
<Card style={{ width: '1rem' }} >
<Card.Img variant="top" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22286%22%20height%3D%22180%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20286%20180%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_16b0e6bd8ef%20text%20%7B%20fill%3A%23999%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A14pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_16b0e6bd8ef%22%3E%3Crect%20width%3D%22286%22%20height%3D%22180%22%20fill%3D%22%23373940%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22107.203125%22%20y%3D%2296.3%22%3E286x180%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" />
<Card.Body>
<Card.Title> Cliente {item.name}</Card.Title>
<Card.Text>
{item.description}
</Card.Text>
</Card.Body>
<ListGroup className="list-group-flush">
<ListGroupItem>Estado:{''}{JSON.stringify(item.state)}</ListGroupItem>
<ListGroupItem>Creado por: {item.createby}</ListGroupItem>
</ListGroup>
<Card.Body>
<Card.Link href="/cliente">Card Link</Card.Link>
<Card.Link href="/cliente">Editar</Card.Link>
</Card.Body>
</Card>
</CardGroup>)
})}
</Container>
</div>
);
}
I dont use react-bootstrap but u can achieve it by doing
<Container>
<div class='row'>
{this.map(value => {
return (
<div class='col-md-6'>
<Card />
</div>
)
});}
</div>
</Container>
This should work
Wrap the map function in row and the returning jsx in col
And dont just write a whole logic in jsx use functions or components

Resources