React child components state is undefined but can see state using console.log - javascript

I have a parent component that gets data from an API end point using fetch. This data displays like it should. The parent component passes an element of an array of objects to the child component. In the child component, when I do a console log I can see the state when it's undefined and when the state is set. The issue that I am having is when I try to access a key of the state (i.e. ticket.title) I get an error saying that ticket is undefined. Any help with would be great.
TicketList
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import TicketDetails from "./TicketDetails"
export default function TicketList() {
const [tickets, updateTickets] = useState([])
const [ticketIndex, updateticketIndex] = useState("0")
useEffect(() => {
async function fetchTickets() {
const response = await fetch("/api/v1/tickets")
const json = await response.json()
updateTickets(json.data)
}
fetchTickets()
}, [])
return (
<Wrapper>
< div >
<TableTitle>
<h3>Tickets</h3>
<button type="submit">Create A Ticket</button>
</TableTitle>
{
tickets.map((ticket, index) => (
<ListInfo key={ticket._id} onClick={() => updateticketIndex(index)}>
<Left>
<p>{ticket.project}</p>
<p>{ticket.title}</p>
<p>{ticket.description}</p>
</Left>
<Right>
<p>{ticket.ticketType}</p>
<p>{ticket.ticketStatus}</p>
<p>{ticket.ticketPriority}</p>
</Right>
</ListInfo>
))
}
</div>
<TicketDetails key={tickets._id} data={tickets[ticketIndex]} />
</Wrapper>
);
}
const Wrapper = styled.div`
display: flex;
background: white;
grid-area: ticketarea;
height: calc(100vh - 4.25rem);
`
const ListInfo = styled.div`
display: flex;
justify-content: space-between;
width: 100%;
padding: .5rem .75rem;
border-bottom: solid 1px #ccc;
`;
const Left = styled.div`
display: flex;
flex: 2;
flex-direction: column;
p {
padding: .25rem;
}
`;
const Right = styled.div`
display: flex;
flex: 1;
flex-direction: column;
align-items: end;
width: 500px;
p {
padding: .25rem;
}
`;
const TableTitle = styled.div`
display: flex;
justify-content: space-between;
padding: 1rem 1rem;
border-bottom: solid 1px #ccc;
button {
padding: .5rem;
}
`;
TicketDetails
import React, { useEffect, useState } from 'react'
// import TicketInfo from './TicketInfo'
import TicketNotes from "./TicketNotes"
import styled from "styled-components"
export default function TicketDetail(data) {
const [ticket, setTicket] = useState(data)
useEffect(() => {
setTicket(data)
}, [data])
console.log(ticket.data)
return (
<Main>
<TicketInfo key={ticket._id}>
<h2>{ticket.title}</h2>
<Info>
<div>
<InfoItem>
<p>Project</p>
<p>{ticket.project}</p>
</InfoItem>
<InfoItem>
<p>Assigned Dev</p>
<p>{ticket.assignedDev}</p>
</InfoItem>
<InfoItem>
<p>Created By</p>
<p>{ticket.submitter}</p>
</InfoItem>
</div>
<div>
<InfoItem>
<p>Type</p>
<p>{ticket.ticketType}</p>
</InfoItem>
<InfoItem>
<p>Status</p>
<p>{ticket.ticketStatus}</p>
</InfoItem>
<InfoItem>
<p>Priority</p>
<p>{ticket.ticketPriority}</p>
</InfoItem>
</div>
</Info>
<Description>{ticket.description}</Description>
</TicketInfo>
<TicketNotes />
<TicketComment>
<textarea name="" id="" cols="30" rows="10" />
<button type="submit">Submit</button>
</TicketComment>
</Main>
)
}
const TicketInfo = styled.div`
margin: .5rem;
h2{
padding: 0.5rem 0;
}
`;
const Description = styled.p`
padding-top: .5rem;
`;
const Info = styled.div`
display: flex;
justify-content: space-between;
border-bottom: solid 1px #ddd;
`;
const InfoItem = styled.section`
margin: .5rem 0;
p:nth-child(1) {
text-transform: uppercase;
color: #ABB1B6;
font-weight: 500;
padding-bottom: .25rem;
}
`;
const Main = styled.div`
background: white;
`
const TicketComment = styled.div`
display: flex;
flex-direction: column;
width: 40rem;
margin: 0 auto ;
input[type=text] {
height: 5rem;
border: solid 1px black;
}
textarea {
border: solid 1px black;
}
button {
margin-top: .5rem;
padding: .5rem;
width: 6rem;
}
`;

There are a few issues here, let's tackle them in order.
Tickets are undefined
When TicketList is mounted, it fetches tickets. When it renders, it immediately renders TicketDetail. The tickets fetch request won't have finished so tickets is undefined. This is why TicketDetail errors out. The solution is to prevent rendering TicketDetail until the tickets are available. You have a few options.
A bare bones approach is to just prevent rendering until the data is available:
{ !!tickets.length && <TicketDetails key={tickets._id} data={tickets[ticketIndex]} />
This uses how logical operators work in JS. In JS falsey && expression returns falsey, and true && expression returns expression. In this case, we turn ticket.length into a boolean. If it is 0 (i.e. not loaded, therefore false), we return false, which React simply discards. If it is greater than 0 (i.e. loaded, therefore true), we render the component.
This doesn't really result in a positive UX though. Ideally this is solved by showing some kind of Loading spinner or somesuch:
{
!!tickets.length
? <TicketDetails . . . />
: <LoadingSpinner />
}
Child data access
In TicketDetail it seems like you meant to destructure data. Currently you are taking the entire prop object and setting it to ticket. Fixing this should resolve the other half of the issue.
Paradigms
You didn't specifically ask for this, but I’d like to back up and ask why you are putting this prop into state? Typically this only done when performing some kind of ephemeral edit, such as pre-populating a form for editing. In your case it looks like you just want to render the ticket details. This is an anti-pattern, putting it into state just adds more code, it doesn’t help you in any way. The convention in React is to just render props directly, state isn't needed.

Related

Passing Props in SolidJS

I came across something weird while trying to pass props in SolidJS. I've created a store using createStore which I pass through the component tree using Context.Provider. I also have the helper function useStore which lets me access the store anywhere in the component tree (I'm experimenting with React design patterns in SolidJS). I have two components Anime.jsx (parent) and EpisodeList.jsx (child). I'm fetching data when the Anime component mounts and then populate the store with the setter provided by createStore.After which I pass the fetched data to EpisodeList. However, accessing the props of EpisodeList returns an empty proxy (Not sure why, but I think the EpisodeList component isn't re-rendered when store is updated with store.currentAnimeData). I've attached the output below of the console.log statements below.
Any help regarding this would be highly appreciated.
###################################
# Anime.jsx (Parent component)
###################################
const Anime = (props) => {
const [store, setStore] = useStore();
const getAnimeData = async () => {
const currentAnimeId = store.currentAnime.animeId;
const currentAnimeData = await firebase.getAnimeData(currentAnimeId);
setStore(
produce((store) => {
store.currentAnimeData = currentAnimeData;
})
);
};
onMount(() => {
getAnimeData();
});
return (
<>
<div
className={css`
width: 100%;
min-height: 20px;
margin: 8px 0px 5px 0px;
padding: 0px 10px;
box-sizing: border-box;
font-size: 20px;
word-wrap: break-word;
line-height: 1;
`}
>
<span
className={css`
font-size: 20px;
color: #e32451;
`}
>
{"Watching: "}
</span>
{store.currentAnime.name}
</div>
<Search></Search>
<EpisodeList animeData={store.currentAnimeData.episodes} />
</>
);
};
#####################################
# EpisodeList.jsx (child component)
#####################################
const EpisodeList = (props) => {
console.log(props);
console.log(props.animeData);
...... # UI stuff
return (
<div
className={css`
width: 100%;
height: 100%;
box-sizing: border-box;
display: flex;
flex-direction: column;
padding-bottom: 5px;
margin-top: 10px;
`}
>
<ScrollActionUp onmousedown={[scroll, true]} onmouseup={onmouseup}>
➭
</ScrollActionUp>
<div
className={css`
width: 100%;
height: 432px;
box-sizing: border-box;
padding: 10px 10px 0px 10px;
overflow: hidden;
`}
ref={scrollRef}
>
<For each={animeData.episodes}>
{(episode, index) => {
return (
<Episode status={episode.watched} episode={episode}></Episode>
);
}}
</For>
</div>
<ScrollActionDown onmousedown={[scroll, false]} onmouseup={onmouseup}>
➭
</ScrollActionDown>
</div>
);
};
###############
# store.jsx
###############
import { createContext, createSignal, useContext } from "solid-js";
import { createStore } from "solid-js/store";
const StoreContext = createContext();
export function ContextProvider(props) {
const [store, setStore] = createStore({});
return (
<StoreContext.Provider value={[store, setStore]}>
{props.children}
</StoreContext.Provider>
);
}
export function useStore() {
return useContext(StoreContext);
}

Trying to Iterate through "Fetch" JSON Data after assigning to State in React.js for a "Slider" component

pretty new to React so don't clown me to hard haha.
Essentially my goal is to fetch the data from my personal JSON server & render that data onto a "Slider" that I am creating.
I am following along with a tutorial and decided to give myself a challenge, the only difference is that where he just imported a data.js file with his data, I wanted to use JSON data / server instead.
The issues is that I'm not sure how to ".map()" through the data for each slide and render to the slider. I have a general idea of how but I'm not fully sure how to implement it correctly in the context of using JSON data with fetch requests.
I have fetched my JSON url and used .thens to string my responses & assign the data to a state setter function. When I console.log the data I receive the object successfully but twice.
Read online that I could use the first variable of state to .map(), attempted and has not worked.
Sorry if this has been touched on before, I have tried everything to find this info before asking but to no avail.
The error I receive is in regards to me using the state variable "slideIndx.map" not being a function.
What can I do here?
import {useState, useEffect} from 'react';
import { ArrowLeftOutlined, ArrowRightOutlined } from "#material-ui/icons";
import styled from "styled-components";
const Container = styled.div`
width: 100%;
height: 95vh;
display: flex;
// background-color: #b3f0ff;
position: relative;
overflow: hidden;
`;
const Arrow = styled.div`
width: 50px;
height: 50px;
background-color: #e6ffff;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
bottom: 0;
left: ${props => props.direction === "left" && "10px"};
right: ${props => props.direction === "right" && "10px"};
margin: auto;
cursor: pointer;
opacity: 0.5;
z-index: 2;
`;
const Wrapper = styled.div`
height: 100%;
display: flex;
transform: translateX(0vw)
`
const Slide = styled.div`
width: 100vw;
height: 100vw;
display: flex;
align-items: center;
background-color: ${props => props.bg};
`
const ImgContainer = styled.div`
height: 100%;
flex:1;
`
const Image = styled.img`
padding-left: 30px;
align-items: left;
`
const InfoContainer = styled.div`
height: 80%;
flex:1;
padding: 30px;
`
const Title = styled.h1`
font-size: 50px
`
const Desc = styled.p`
margin: 50px 0px;
font-size: 20px;
font-weight: 500;
letter-spacing: 3px;
`
const Button = styled.button`
padding: 10px;
font-size: 20px;
background-color: transparent;
cursor: pointer;
`
const Slider = () => {
const [slideIndx, setSlideIndx] = useState(0);
const fetchSliderItems = () => {
fetch('http://localhost:3000/sliderItems')
.then(resp => resp.json())
.then(data => {
console.log(data)
setSlideIndx(data)
})
}
useEffect(() => {fetchSliderItems()}, [])
const handleClick = (direction) => {}
return (
<Container>
<Arrow direction="left" onClick={() => handleClick("left")}>
<ArrowLeftOutlined />
</Arrow>
// Here is where I am attempting to map over the items.
<Wrapper>
{fetchSliderItems.map((item) => (
<Slide bg={item.bg}>
<ImgContainer>
<Image src={item.img}/>
</ImgContainer>
<InfoContainer>
<Title>{item.title}</Title>
<Desc>{item.desc}</Desc>
<Button>SHOP NOW</Button>
</InfoContainer>
</Slide>
))}
</Wrapper>
<Arrow direction="right" onClick={() => handleClick("right")}>
<ArrowRightOutlined />
</Arrow>
</Container>
)
}
export default Slider
{
"sliderItems": [
{
"id": 1,
"img": "../images/model1.png",
"title": "SPRING CLEANING",
"desc": "DONT MISS OUR BEST COLLECTION YET! USE #FLATIRON10 TO RECEIVE 10% OFF YOUR FIRST ORDER",
"bg": "b3ecff"
},
{
"id": 2,
"img": "https://i.ibb.co/DG69bQ4/2.png",
"title": "SHOW OFF HOW YOU DRESS",
"desc": "WITH OUR HUGE SELECTION OF CLOTHES WE FIT ALL YOUR STYLING NEEDS",
"bg": "ccf2ff"
},
{
"id": 3,
"img": "../images/model1.png",
"title": "POPULAR DEALS",
"desc": "RECEIVE FREE SHIPPING ON ALL ORDERS OVER $50!",
"bg": "fe6f9ff"
}
]
}
You should share the error you're getting. But based on the second screenshot, it looks like your array is wrapped in a sliderItems object.
You want a raw array when you .map. So maybe try setting your slideIndx to the raw array by doing something like:
setSlideIndx(data.sliderItems)
Try confirming the shape of your state by console logging above your return with:
console.log(slideIndx)
You're calling map from fetchSliderItems.map, but fetchSliderItems is a function, not an array. You need to call map from the array containing the data, which in your case is slideIndx.sliderItems.
What happens in your code is const [slideIndx, setSlideIndx] = useState(0); initializes slideIndx to 0. When useEffect runs fetchSliderItems, you'll fetch the data and eventually the line setSlideIndx(data) assigns data to slideIndx. Because your data is an object that holds and array in the sliderItems property, the array can now be accessed in slideIndx.sliderItems.
So fist thing you should do to fix it is change the useState line to const [slideIndx, setSlideIndx] = useState([]);, because you want your state variable to be an array. Then when you fetch the data you want to call setSlideIndx(data.sliderItems) to assign your data to slideIndx. Finally, in your jsx return you should use slideIndx.map.

React: Moving component to different div on click

I'm very new to React so any advice would be appreciated on how to move an agent thumbnail to the teamComp div when it is clicked.
I'm also lost as to how to tackle filtering the data through a dropdown menu. Like how would I update the page without refreshing so that only the agents with the selected roles appear.
Anything would help, like I said before, I am a complete beginner to React and feel like I am underutilizing a lot of what makes React powerful.
App.js
import { useEffect, useMemo, useState } from "react";
import AgentCard from "./components/agentCard";
import Select from "react-select"
function App() {
const options = useMemo(
() => [
{value: "controller", label: "Controller"},
{value: "duelist", label: "Duelist"},
{value: "initiator", label: "Initiator"},
{value: "sentinel", label: "Sentinel"},
],
[]
);
const [agentDetails, setAgentDetails] = useState([]);
const getAllAgents = async () => {
const res = await fetch("https://valorant-api.com/v1/agents/");
const results = await res.json();
const agentNames = [],
agentImages = [],
agentRoles = [],
agentDetails = [];
for (let i = 0; i < Object.keys(results["data"]).length; i++) {
if (results["data"][i]["developerName"] != "Hunter_NPE") {
agentNames.push(results["data"][i]["displayName"]);
agentImages.push(results["data"][i]["displayIcon"]);
agentRoles.push(results["data"][i]["role"]["displayName"]);
}
else {
continue;
}
}
for (let i = 0; i < agentNames.length; i++) {
agentDetails[i] = [agentNames[i], [agentImages[i], agentRoles[i]]];
}
agentDetails.sort();
setAgentDetails(agentDetails);
};
useEffect(() => {
getAllAgents();
}, []);
return (
<div className="app-container">
<h2>Valorant Team Builder</h2>
<div className="teamComp">
</div>
<Select options={options} defaultValue={options} isMulti/>
<div id="agent_container" className="agent-container">
{agentDetails.map((agentDetails) => (
<AgentCard
img={agentDetails[1][0]}
name={agentDetails[0]}
role={agentDetails[1][1]}
/>
))}
</div>
</div>
);
}
export default App;
agentCard.js
import React from 'react'
const agentCard = ({role, name, img}) => {
return (
<div className="card-container">
<div className="img-container">
<img src={img} alt={name} />
</div>
<div className="info">
<h3 className="name">{name}</h3>
<small className="role"><span>Role: {role}</span></small>
</div>
</div>
)
}
export default agentCard
index.css
#import url('https://fonts.googleapis.com/css?family=Muli&display=swap');
#import url('https://fonts.googleapis.com/css?family=Lato:300,400&display=swap');
* {
box-sizing: border-box;
}
body {
background: #EFEFBB;
background: -webkit-linear-gradient(to right, #D4D3DD, #EFEFBB);
background: linear-gradient(to right, #D4D3DD, #EFEFBB);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: 'Lato';
margin: 0;
}
h1 {
letter-spacing: 3px;
}
.agent-container {
display: flex;
flex-wrap: wrap;
align-items: space-between;
justify-content: center;
margin: 0 auto;
max-width: 1200px;
}
.app-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
padding: 3rem 0.5rem;
}
.card-container {
background-color: #eee;
border-radius: 20px;
box-shadow: 0 3px 15px rgba(100, 100, 100, 0.5);
margin: 10px;
padding: 20px;
text-align: center;
}
.card-container:hover {
filter: brightness(70%);
transition: all 150ms ease;
}
.img-container img {
margin-top: 1.5rem;
height: 128px;
width: 128px;
}
.name {
margin-bottom: 0.2rem;
}
.teamComp h3 {
float: left;
}
Moving cards
To move a card to a different list you need a new state array that will represent "the members of the team". Something like:
const [team, setTeam] = useState([]);
Render the items in team inside the "teamComp" <div>, the same way you do it in the agent container.
Then add the new function prop to the card and use it in the onClick handler in the card <div>:
<AgentCard
key={agentDetails[0]}
img={agentDetails[1][0]}
name={agentDetails[0]}
role={agentDetails[1][1]}
handleClick={moveToTeam}
/>
...
<div className="card-container" onClick={() => handleClick(name)}>
and in this function, add the agentDetails item to the team state and remove it from the agentDetails state. Make sure that you supply new arrays when setting state:
const moveToTeam = (name) => {
const newTeam = [...team, agentDetails.find((agent) => agent[0] === name)];
const newAgentDetails = agentDetails.filter((agent) => agent[0] !== name);
setTeam(newTeam);
setAgentDetails(newAgentDetails);
};
Filtering
For filtering you need another state that contains all selected options:
const [options, setOptions] = useState(allOptions);
where allOptions is an array of all available options, and it should not change.
Add the onChange handler to the <Select> component:
<Select
options={allOptions}
onChange={(selectedOptions) => setOptions(selectedOptions)}
defaultValue={allOptions}
isMulti
/>
and finally use options to filter cards:
<div id="agent_container" className="agent-container">
{agentDetails
.filter(
(agentDetails) =>
options.filter((option) => option.label === agentDetails[1][1])
.length > 0
)
.map((agentDetails) => (
<AgentCard
key={agentDetails[0]}
img={agentDetails[1][0]}
name={agentDetails[0]}
role={agentDetails[1][1]}
handleClick={moveToTeam}
/>
))}
</div>
You can see the complete example on codesandbox.
I left most of the names in place, although I think using agentDetails for different things is confusing. The data structures can also be improved, but I left them unchanged as well.

My component re-render after i try to search for an element in a useState array

I am currently building a React project, so I made a search Input and when I type something in that Input field my hole component re-renders causing an API recall and deleting the text in my Input. I tried merging both the search component with Home component and the same problem appears.
I want my component to call the api only one time, and I am trying to filter the response depending on the input type.
please help!!
Here is my Home component:
import { useContext, useEffect, useState } from 'react';
import styled from 'styled-components';
import CountryThumb from '../Components/CountryThumb';
import ThemeContext from '../Components/ColorPalette';
import { Themes } from '../Components/ColorPalette';
import Search from '../Components/Search';
import Filter from '../Components/Filter';
const Grid = styled.main`
width: 100%;
display: grid;
grid-template-columns: repeat(4, 1fr);
column-gap: 60px;
row-gap: 40px;
#media (max-width: 375px) {
grid-template-columns: repeat(1, 1fr);
}
`;
export default function Home() {
const [Countries, setCountries] = useState([]);
const [SearchTerms, setSearchTerms] = useState('');
const { Theme } = useContext(ThemeContext);
const style = Theme == 'light' ? Themes.light : Themes.dark;
useEffect(() => {
getCountries();
}, []);
const Main = styled.main`
display: flex;
flex-wrap: wrap;
padding: 20px 100px;
background-color: ${Theme == 'light' ? style.background : style.background};
#media (max-width: 375px) {
padding: 40px 25px;
}
`;
const getCountries = () => {
axios
.get('https://restcountries.eu/rest/v2/all')
.then((res) => setCountries(res.data))
.catch((err) => console.log(err));
};
return (
<>
<Main>
<Search handleSearch={(e) => setSearchTerms(e.target.value)} />
<Filter />
<Grid>
{Countries.slice(0, 12)
.filter((e) => {
if (SearchTerms == '') {
return e;
} else if (
e.name.toLowerCase().includes(SearchTerms.toLowerCase())
) {
return e;
}
})
.map((e) => (
<CountryThumb props={e} />
))}
</Grid>
</Main>
</>
);
}
And here is my Search component:
import { useContext, useState } from 'react';
import styled from 'styled-components';
import ThemeContext, { Themes } from './ColorPalette';
function Search({ handleSearch }) {
const { Theme } = useContext(ThemeContext);
const style = Theme == 'light' ? Themes.light : Themes.dark;
const Svg = styled.svg`
width: 24px;
height: 24px;
color: ${style.text};
`;
const Wrapper = styled.div`
background-color: ${style.element};
border-radius: 5px;
box-shadow: 0 5px 10px ${style.shadow};
display: flex;
align-items: center;
padding: 0 20px;
margin: 40px 0;
`;
const CInput = styled.input`
border: none;
outline: none;
padding: 15px 120px 15px 20px;
font-size: 1rem;
color: ${style.text};
background: none;
`;
return (
<>
<Wrapper>
<Svg
xmlns='http://www.w3.org/2000/svg'
class='h-6 w-6'
fill='none'
viewBox='0 0 24 24'
stroke='currentColor'
>
<path
strokeLinecap='round'
strokeLinejoin='round'
strokeWidth='2'
d='M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z'
/>
</Svg>
<CInput
type='text'
name='Search'
onInput={handleSearch}
placeholder='Search for a country ...'
/>
</Wrapper>
</>
);
}
export default Search;
Whenever you change anything in state your component will rerender so it is normal behaviour. However you have dependency array in useEffect that calls api so this function should run only one time, maybe you didnt have array before and forgot to save.

ReactJS - pass object keys and values as props to div

In my Class component Field.jsx render(), I'm expanding my <Position> component using <Flipper>, (an abstracted flip animation), like so:
import { Flipper, Flipped } from 'react-flip-toolkit'
import { Position } from "./Position";
import "./css/Position.css";
class Field extends Component {
constructor(props) {
super(props);
this.state = {
fullScreen: false,
};
}
toggleFullScreen() {
this.setState({ fullScreen: !this.state.fullScreen });
}
...
render() {
const { players } = this.props;
const { fullScreen } = this.state;
if(players){
return (
<div className="back">
<div className="field-wrapper" >
<Output output={this.props.strategy} />
<Flipper flipKey={fullScreen}>
<Flipped flipId="player">
<div className="field-row">
{this.getPlayersByPosition(players, 5).map((player,i) => (
<Position
key={i}
className={fullScreen ? "full-screen-player" : "player"}
getPositionData={this.getPositionData}
toggleFullScreen={this.toggleFullScreen.bind(this)}
>{player.name}</Position>
))}
</div>
</Flipped>
</Flipper>
</div>
</div>
);
}else{
return null}
}
When I render it, I get clickable items from the mapped function getPlayersByPosition(), like so:
And if I click on each item, it expands to a div with player name:
Which is passed as props.children at component <div>
Position.jsx
import React from "react";
import "./css/Position.css";
export const Position = props => (
<div
className={props.className}
onClick={() => {
props.getPositionData(props.children);
props.toggleFullScreen();
console.log(props.getPositionData(props.children))
}}
>
{props.children}
</div>
);
getPositionData(), however, returns an object with many items on its turn, as seen by console above:
{matches: 7, mean: 6.15, price: 9.46, value: 0.67, G: 3, …}
QUESTION:
How do I pass and print theses other props keys and values on the expanded purple div as text?, so as to end with:
Patrick de Paula
matches: 7
mean: 6.15
price:9.46
....
NOTE:
Position.css
.position-wrapper {
height: 4em;
display: flex;
justify-content: center;
align-items: center;
font-weight: lighter;
font-size: 1.4em;
color: #888888;
flex: 1;
/*outline: 1px solid #888888;*/
}
.player {
height: 4em;
width: 4em;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
font-weight: lighter;
font-size: 1.4em;
/*background-color: #66CD00;*/
color: #ffffff;
}
.full-screen-player {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
cursor: pointer;
background-image: linear-gradient(
45deg,
rgb(121, 113, 234),
rgb(97, 71, 182)
);
}
Looks like the props are all set & ready to be print as seen on your console. You can access them via props.getPositionData(props.children).property_name_here or destructure them
export const Position = props => {
const { matches, mean, price } = props.getPositionData(props.children);
return (
<div
className={props.className}
onClick={() => {
props.getPositionData(props.children);
props.toggleFullScreen();
console.log(props.getPositionData(props.children))
}}
>
<p>Name: {props.children}</p>
<p>Matches: {matches}</p>
<p>Mean: {mean}</p>
<p>Price: {price}</p>
</div>
)
}
Regarding the issue on the fullScreen prop (see comments section):
Is there a way to print them ONLY after toggleFullScreen()
Since you already have a state on the Field component which holds your fullScreen value, on your Field component, you need to pass the fullScreen prop as well to the Position component. e.g., fullScreen={this.state.fullScreen}. Back on Position component, have some condition statements when you are rendering.
Example:
<>
{props.fullScreen &&
<p>Name: {props.children}</p>
}
</>

Categories

Resources