I am writing a page showing current posts, I use Contentful CMS and fetch the GraphQl API. I have normal string types in the Content model, but the last one is rich text.
I'm going to add a card with the post's name, title, date, and just a short post text. In this case, I reset the rich text formatting to make it behave like normal text.
When I try to add a list of regular strings in a component everything works, but when I add functions with a rich text render, it returns an error:
Cannot read properties of undefined (reading 'props')
I've tried different ways to do it, and it still won't work. I want to combine one query that fetches normal strings and another that fetch the raw Rich text and render Rich text without formatting
Visually, the list should look like this:
And my error displayed in Gatsby looks like this:
Finally, I would like to show you, most importantly - my code:
import React from "react"
import { graphql } from 'gatsby'
import { BLOCKS, MARKS } from "#contentful/rich-text-types"
import { renderRichText } from "gatsby-source-contentful/rich-text"
import Layout from "../components/base/layout"
import {
PageWrapper,
BlogCardWrapper,
BlogCardElement,
ThumbnailImage,
ContentInlineWrapper,
PreContentParagraph,
ReadMoreParagraph,
BlogTitleHeader,
BlogDateParagraph,
} from "../styles/aktualnosci.style"
import { Headers } from "../utils/data/headersData"
import H1 from "../components/headers/h1"
const AktualnosciPage = ({ data }) => {
const articles = data.allContentfulArtykul.edges
const post = this.props.data.allContentfulArtykul.edges[0].node.content
const option = {
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: node => {
return <img/>
},
[BLOCKS.HEADING_1]: (node, children) => {
return <p style={{padding: '0', margin: '0', display: 'inline-block'}}>{children}</p>
},
[BLOCKS.HEADING_5]: (node, children) => {
return <p style={{padding: '0', margin: '0', display: 'inline-block'}}>{children}</p>
},
[BLOCKS.PARAGRAPH]: (node, children) => {
return <p style={{padding: '0', margin: '0', display: 'inline-block'}}>{children}</p>
},
[BLOCKS.QUOTE]: (node, children) => {
return <p style={{padding: '0', margin: '0', display: 'inline-block'}}>{children}</p>
},
[BLOCKS.UL_LIST]: (node, children) => {
return <p style={{padding: '0', margin: '0', display: 'inline-block'}}>{children}</p>
},
[BLOCKS.LIST_ITEM]: (node, children) => {
return <p style={{padding: '0', margin: '0', display: 'inline-block'}}>{children}</p>
},
},
renderMark: {
[MARKS.BOLD]: (node, children) => {
return <p style={{fontWeight: '100'}}>{children}</p>
},
}
}
const output = renderRichText(post, option)
return (
<Layout>
<PageWrapper>
<H1 name={ Headers.Aktualnosci }/>
<BlogCardWrapper>
{articles.reverse().map(({node}) => {
return (
<div key={node.slug}>
<a href={"/aktualnosci/" + node.slug}>
<BlogCardElement>
<ThumbnailImage
className="j10_dfg4gvBDG"
src={node.thumbnailPhoto.fluid.src}
srcSet={node.thumbnailPhoto.fluid.srcSet}
/>
<ContentInlineWrapper>
<BlogTitleHeader>{node.title}</BlogTitleHeader>
<PreContentParagraph>{output}</PreContentParagraph>
<BlogDateParagraph>{node.createdAt}</BlogDateParagraph>
</ContentInlineWrapper>
<ReadMoreParagraph className="j5_dfg4gvBDG">Czytaj więcej <span style={{color: '#BF1E2D', fontSize: '11px'}}>➤</span></ReadMoreParagraph>
</BlogCardElement>
</a>
</div>
)
})}
</BlogCardWrapper>
</PageWrapper>
</Layout>
)
}
export const query = graphql`
query {
allContentfulArtykul {
edges {
node {
id
thumbnailPhoto {
fluid {
src
srcSet
}
}
title
slug
content {
raw
references {
... on ContentfulAsset {
__typename
contentful_id
fixed(width: 200) {
src
srcSet
}
}
}
}
createdAt(formatString: "YYYY-MM-DD")
}
}
}
}
`
export default AktualnosciPage
If something is missing, please let me know.
You are destructuring your queried data in the component declaration:
const AktualnosciPage = ({ data }) => {}
You are taking props.data directly with { data }
Moreover, because you are in a non-class-based component (you are using a functional component), the use of this is strictly restricted.
You should do directly:
const post = data.allContentfulArtykul.edges[0].node.content
As you do in the line above taking data.allContentfulArtykul.edges.
For a more succinct approach, you can also do:
const articles = data.allContentfulArtykul.edges
const post = articles[0].node.content
Related
My app is a dashboard of MUI <Card />s that can be dragged-and-dropped (d&d) to reorder them. The d&d logic is implemented using react-dnd and has been working well so far.
However, when I add a <DataGridPro /> as the child of a draggable <Card />, the datagrid's native Column ordering - which also is done by dragging-and-dropping - breaks. Dragging a column once or twice generates the following crash:
Invariant Violation
Cannot call hover while not dragging.
▼ 5 stack frames were expanded.
at invariant (https://bfz133.csb.app/node_modules/
react-dnd/invariant/dist/index.js:19:15
checkInvariants
https://bfz133.csb.app/node_modules/dnd-core/dist/actions/dragDrop/hover.js:33:40
DragDropManagerImpl.hover
https://bfz133.csb.app/node_modules/dnd-core/dist/actions/dragDrop/hover.js:18:5
Object.eval [as hover]
https://bfz133.csb.app/node_modules/dnd-core/dist/classes/DragDropManagerImpl.js:25:38
HTML5BackendImpl.handleTopDrop
https://bfz133.csb.app/node_modules/react-dnd-html5-backend/dist/HTML5BackendImpl.js:455:20
▲ 5 stack frames were expanded.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.
This error overlay is powered by `react-error-overlay` used in `create-react-app`.
You can begin dragging, the crash only happens when you let go of the mouse button.
The expected behavior is that I should be able to d&d the columns, to change their order, without issues.
Things I've tried
Removing the <DataGridPro /> and replacing that <Card /> with a text-type Card (see the code in the sandbox below) shows that d&d logic works fine with no crashes;
Disabling my app's d&d by commenting out all the relevant code causes the <DataGridPro />'s colum reordering to work as expected;
The above suggests the root cause lies in having both D&Ds work without causing an internal conflict in react-dnd, which led to me trying:
Browsing the documentation to find a way to instruct the component to use my own DndProvider or DndManager, but I couldn't find that in the API - sorry if I misread it!
Googling for the error message "Cannot call hover while not dragging", while limiting myself to contexts including the MUI library or react-dnd, yielded limited results. I found a Chrome bug that was fixed on v. 77.0.3865.120, my Chrome version is 101.0.4951.64 .
EDIT: Found this bug, but it's closed. Should I open a new one? I'd like some input on this, as I wouldn't like to bother the developers if the problem is in my code.
Minimum verified reproducible example
I made a sandbox! Click here to see it
Datagrid Component:
import React from "react";
import { DataGridPro } from "#mui/x-data-grid-pro";
import { useDemoData } from "#mui/x-data-grid-generator";
export function MyDatagridPro() {
const { data } = useDemoData({
dataSet: "Commodity",
rowLength: 5,
maxColumns: 6
});
return <DataGridPro {...data} />;
}
Card widget:
import React, { useRef } from "react";
import {
Card,
CardHeader,
CardContent,
Grid,
Typography,
Divider
} from "#mui/material";
import { useDrag, useDrop } from "react-dnd";
import { MyDatagridPro } from "./MyDatagridPro";
export function MyContentCard(props) {
const domRef = useRef(null);
const [{ isDragging }, dragBinder, previewBinder] = useDrag(
() => ({
type: "mycard",
item: () => ({
orderIndex: props.orderIndex
}),
collect: (monitor) => ({
isDragging: monitor.isDragging()
})
}),
[props]
);
const [{ handlerId, isOver }, dropBinder] = useDrop(
() => ({
accept: "mycard",
collect: (monitor) => ({
handlerId: monitor.getHandlerId(),
isOver: !!monitor.isOver()
}),
canDrop: (item, monitor) => {
if (!domRef.current) return false;
const draggingOrderIndex = item.orderIndex;
const hoveringOrderIndex = props.orderIndex;
if (draggingOrderIndex === hoveringOrderIndex) return false;
const hoverRectangleBound = domRef.current?.getBoundingClientRect();
const [hoverItemX, hoverItemY] = [
hoverRectangleBound.right - hoverRectangleBound.left,
hoverRectangleBound.bottom - hoverRectangleBound.top
];
const mousePosition = monitor.getClientOffset();
const [hoverMouseX, hoverMouseY] = [
mousePosition.x - hoverRectangleBound.left,
mousePosition.y - hoverRectangleBound.top
];
if (
(hoverMouseX < 0 || hoverMouseX > hoverItemX) &&
(hoverMouseY < 0 || hoverMouseY > hoverItemY)
) {
return false;
}
return true;
},
drop: (item) => {
props.swapper(item.orderIndex, props.orderIndex);
}
}),
[props]
);
return (
<Grid item xs={5}>
<Card
ref={(element) => {
if (element) {
domRef.current = element;
previewBinder(dropBinder(domRef));
}
}}
sx={{
height: `calc(6 * 4.5rem)`,
opacity: isDragging ? 0.3 : 1,
display: "flex",
flexDirection: "column",
border: isOver ? "2px solid rgba(0,0,0,0.5);" : ""
}}
data-handler-id={handlerId}
>
<CardHeader ref={dragBinder} title={props.title} />
<Divider />
<CardContent
sx={{
height: "100%",
display: "flex",
flexDirection: "column"
}}
>
{props.type === "text" && <Typography>{props.content}</Typography>}
{props.type === "datagrid" && <MyDatagridPro />}
</CardContent>
</Card>
</Grid>
);
}
export default MyContentCard;
App.js:
import React, { useState } from "react";
import { Grid } from "#mui/material";
import { createDragDropManager } from "dnd-core";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import { MyContentCard } from "./MyContentCard";
export const dndManager = createDragDropManager(HTML5Backend);
export default function App() {
const [cards, setCards] = useState([
{
type: "datagrid",
title: "Card 01 - A MUI DataGridPro",
content: ""
},
{
type: "text",
title: "Card 02 - Some text",
content: "Text that belongs to card 2"
}
]);
function swapCards(indexA, indexB) {
const newState = cards.slice();
const cardA = Object.assign({}, cards[indexA]);
newState[indexA] = Object.assign({}, cards[indexB]);
newState[indexB] = cardA;
setCards(newState);
}
return (
<DndProvider manager={dndManager}>
<Grid
container
spacing={1}
columns={10}
p={2}
pb={3}
mt={0}
mb={0}
// flex="1 1 auto"
overflow="auto"
sx={{
backgroundColor: "lightgray"
}}
>
{cards.map((card, i) => {
return (
<MyContentCard
key={i}
type={card.type}
title={card.title}
content={card.content}
orderIndex={i}
swapper={swapCards}
/>
);
})}
</Grid>
</DndProvider>
);
}
I'm very new to coding and trying to figure out an issue I have come across.
I am using axios to pull a json file and store it in a state. (I am also using Redux to populate the form)
Then I am using .map() to dissect the array and show one value from within each object in the array.
example json:
unit :
[
{
designName : x,
quantity : 0,
},
{
designName : y,
quantity : 0,
},
{
designName : z,
quantity : 0,
}
]
I have then added an input to select the quantity of the value mapped and now I want to give that value back to the state, in order to send the entire modified json back to the API with Axios.
I feel like I'm close but I'm unsure what I need to do with the handleQuantity function.
Here's my code:
import React, { Component } from 'react';
import store from '../../redux_store'
import axios from 'axios';
import { Button, Card } from 'react-bootstrap'
import { Link } from 'react-router-dom'
store.subscribe(() => {
})
class developmentSummary extends Component {
constructor(props) {
super(props)
this.state = {
prjName: store.getState()[0].developmentName,
units: []
}
}
componentDidMount() {
axios.get('https://API')
.then(
res => {
console.log(res)
this.setState({
units: res.data.buildings
})
console.log(this.state.units.map(i => (
i.designName
)))
}
)
}
handleQuantity() {
}
render() {
return (
<>
<div className="Text2">
{this.state.prjName}
</div>
<div className="Text2small">
Please select the quantity of buildings from the list below
</div>
<ul>
{this.state.units.map((object, i) => (
<div className="Card-center">
<Card key={i} style={{ width: "50%", justifyContent: "center" }}>
<Card.Body>{object.designName}</Card.Body>
<Card.Footer>
<input
className="Number-picker"
type="number"
placeholder="0"
onChange={this.handleQuantity}
/>
</Card.Footer>
</Card>
</div>
))}
</ul>
Thanks in advance!
You have to pass the change event, unit object and the index to handleQuantity and then paste your changed unit as new object in between unchanged units.
Here is the code:
<input
className="Number-picker"
type="number"
placeholder="0"
onChange={(event) => this.handleQuantity(event, object, i)}
/>;
And the code for handleQuantity
handleQuantity = (event, unit, index) => {
const inputedNumber = +event.target.value; // get your value from the event (+ converts string to number)
const changedUnit = { ...unit, quantity: inputedNumber }; // create your changed unit
// place your changedUnit right in between other unchanged elements
this.setState((prevState) => ({
units: [
...prevState.units.slice(0, index),
changedUnit,
...prevState.units.slice(index + 1),
],
}));
}
I want to choose just featured posts (3 posts) from graphql for then show this in my blog page, so I limit query to only three results but in case that I just have one post the site will fail.
Because, I'm using a staticquery for get data, in this case I should to use render attribute in the staticquery component and I can not to use a if block on the attribute and when graphql won't find other posts it gonna fail.
Here the code:
featured-posts.js
import React from "react"
import MiniFeatured from "../components/minifeatured"
import { StaticQuery, Link, graphql } from "gatsby"
const Featured = () => {
return (
<StaticQuery
query={graphql`
query FeaturedBlogsport {
allMarkdownRemark (
limit: 3
sort: {order: DESC, fields: [frontmatter___date]}
filter: {frontmatter: {featured: {eq: true}}}
) {
edges {
node {
frontmatter {
title
description
post_image
}
fields {
slug
}
}
}
}
}
`}
render={data => (
<div className="mainBlogposts">
<div
className="featuredBlogpost"
style={{backgroundImage: `url('${data.allMarkdownRemark.edges[0].node.frontmatter.post_image}')`}}
>
<div className="featuredBlogpostContent">
<Link to={`https://strokequote.co/${data.allMarkdownRemark.edges[0].node.fields.slug}`}>
<h1 className="featuredBlogpostTitle">
{data.allMarkdownRemark.edges[0].node.frontmatter.title}
</h1>
<h6 className="featuredBlogpostAuthor">
{data.allMarkdownRemark.edges[0].node.frontmatter.description}
</h6>
</Link>
</div>
</div>
<div className="minifeaturedBlogpostsContainer">
<MiniFeatured
title={data.allMarkdownRemark.edges[1].node.frontmatter.title}
description={data.allMarkdownRemark.edges[1].node.frontmatter.description}
postImage={data.allMarkdownRemark.edges[1].node.frontmatter.post_image}
slug={data.allMarkdownRemark.edges[1].node.fields.slug}
/>
<MiniFeatured
title={data.allMarkdownRemark.edges[2].node.frontmatter.title}
description={data.allMarkdownRemark.edges[2].node.frontmatter.description}
postImage={data.allMarkdownRemark.edges[2].node.frontmatter.post_image}
slug={data.allMarkdownRemark.edges[2].node.fields.slug}
/>
</div>
</div>
)}
/>
)
}
export default Featured
PDD. Minifeatured are secondary featured posts in other components.
PDD 2. Sorry about my English, I'm still learning
I believe that find found a solution. With useStaticQuery from gatsby I can do something like this:
const Featured = () => {
const { edges } = FeaturedPostsQuery()
return (
<div className="mainBlogposts">
<div
className="featuredBlogpost"
style={{backgroundImage: `url('${edges[0].node.frontmatter.post_image}')`}}
>
<div className="featuredBlogpostContent">
<Link to={`https://strokequote.co/${edges[0].node.fields.slug}`}>
<h1 className="featuredBlogpostTitle">
{edges[0].node.frontmatter.title}
</h1>
<h6 className="featuredBlogpostAuthor">
{edges[0].node.frontmatter.description}
</h6>
</Link>
</div>
</div>
<div className="minifeaturedBlogpostsContainer">
<MiniFeatured
title={edges[1].node.frontmatter.title}
description={edges[1].node.frontmatter.description}
postImage={edges[1].node.frontmatter.post_image}
slug={edges[1].node.fields.slug}
/>
<MiniFeatured
title={edges[2].node.frontmatter.title}
description={edges[2].node.frontmatter.description}
postImage={edges[2].node.frontmatter.post_image}
slug={edges[2].node.fields.slug}
/>
</div>
</div>
)
}
export default Featured
export const FeaturedPostsQuery = () => {
const { allMarkdownRemark } = useStaticQuery(graphql`
query FeaturedBlogsport {
allMarkdownRemark (
limit: 3
sort: {order: DESC, fields: [frontmatter___date]}
filter: {frontmatter: {featured: {eq: true}}}
) {
edges {
node {
frontmatter {
title
description
post_image
}
fields {
slug
}
}
}
}
}
`)
return allMarkdownRemark
}
Why do you use a StaticQuery to achieve this? You can simply do it by using a regular GraphQL query, like:
import { graphql, Link } from 'gatsby';
import React from 'react';
const Featured = ({ data }) => {
return <div>
{data.allMarkdownRemark.edges.map(({ node: post }) => {
return <div className="mainBlogposts">
<div className="featuredBlogpost"
style={{ backgroundImage: `url(${post.frontmatter.post_image})` }}>
<div className="featuredBlogpostContent">
<Link to={`https://strokequote.co/${post.fields.slug}`}>
<h1 className="featuredBlogpostTitle">
{post.frontmatter.title}
</h1>
<h6 className="featuredBlogpostAuthor">
{post.frontmatter.description}
</h6>
</Link>
</div>
</div>
</div>;
})}
</div>;
};
export const AboutMeData = graphql`
query FeaturedBlogsport {
allMarkdownRemark (
limit: 3
sort: {order: DESC, fields: [frontmatter___date]}
filter: {frontmatter: {featured: {eq: true}}}
) {
edges {
node {
frontmatter {
title
description
post_image
}
fields {
slug
}
}
}
}
}
`;
What I've done is simply get all the 3 articles and loop through them, using your HTML structure. I aliased the node as a post using a destructuring inside the iterable variable in { node: post } but ideally, all that bunch of HTML should be another isolated component (it's really huge) and you should pass post as a prop to them but for now, it will work.
The snippet above will simply print the amount of post that the query can fetch, no matter if it's 1, 2, or 3.
Besides, it's cleaner than accessing manually each array position ([0], [1], etc).
The function is getting the value of a button click as props. Data is mapped through to compare that button value to a key in the Data JSON called 'classes'. I am getting all the data correctly. All my console.logs are returning correct values. But for some reason, I cannot render anything.
I've tried to add two return statements. It is not even rendering the p tag with the word 'TEST'. Am I missing something? I have included a Code Sandbox: https://codesandbox.io/s/react-example-8xxih
When I click on the Math button, for example, I want to show the two teachers who teach Math as two bubbles below the buttons.
All the data is loading. Just having an issue with rendering it.
function ShowBubbles(props){
console.log('VALUE', props.target.value)
return (
<div id='bubbles-container'>
<p>TEST</p>
{Data.map((item,index) =>{
if(props.target.value == (Data[index].classes)){
return (
<Bubble key={index} nodeName={Data[index].name}>{Data[index].name}
</Bubble>
)
}
})}
</div>
)
}
Sandbox Link: https://codesandbox.io/embed/react-example-m1880
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
const circleStyle = {
width: 100,
height: 100,
borderRadius: 50,
fontSize: 30,
color: "blue"
};
const Data = [
{
classes: ["Math"],
name: "Mr.Rockow",
id: "135"
},
{
classes: ["English"],
name: "Mrs.Nicastro",
id: "358"
},
{
classes: ["Chemistry"],
name: "Mr.Bloomberg",
id: "405"
},
{
classes: ["Math"],
name: "Mr.Jennings",
id: "293"
}
];
const Bubble = item => {
let {name} = item.children.singleItem;
return (
<div style={circleStyle} onClick={()=>{console.log(name)}}>
<p>{item.children.singleItem.name}</p>
</div>
);
};
function ShowBubbles(props) {
var final = [];
Data.map((item, index) => {
if (props.target.value == Data[index].classes) {
final.push(Data[index])
}
})
return final;
}
function DisplayBubbles(singleItem) {
return <Bubble>{singleItem}</Bubble>
}
class Sidebar extends Component {
constructor(props) {
super(props);
this.state = {
json: [],
classesArray: [],
displayBubble: true
};
this.showNode = this.showNode.bind(this);
}
componentDidMount() {
const newArray = [];
Data.map((item, index) => {
let classPlaceholder = Data[index].classes.toString();
if (newArray.indexOf(classPlaceholder) == -1) {
newArray.push(classPlaceholder);
}
// console.log('newArray', newArray)
});
this.setState({
json: Data,
classesArray: newArray
});
}
showNode(props) {
this.setState({
displayBubble: true
});
if (this.state.displayBubble === true) {
var output = ShowBubbles(props);
this.setState({output})
}
}
render() {
return (
<div>
{/* {this.state.displayBubble ? <ShowBubbles/> : ''} */}
<div id="sidebar-container">
<h1 className="sidebar-title">Classes At School</h1>
<h3>Classes To Search</h3>
{this.state.classesArray.map((item, index) => {
return (
<button
onClick={this.showNode}
className="btn-sidebar"
key={index}
value={this.state.classesArray[index]}
>
{this.state.classesArray[index]}
</button>
);
})}
</div>
{this.state.output && this.state.output.map(item=><DisplayBubbles singleItem={item}/>)}
</div>
);
}
}
ReactDOM.render(<Sidebar />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
The issue here is ShowBubbles is not being rendered into the DOM, instead (according the sandbox), ShowBubbles (a React component) is being directly called in onClick button handlers. While you can technically do this, calling a component from a function will result in JSX, essentially, and you would need to manually insert this into the DOM.
Taking this approach is not very React-y, and there is usually a simpler way to approach this. One such approach would be to call the ShowBubbles directly from another React component, e.g. after your buttons using something like:
<ShowBubbles property1={prop1Value} <etc...> />
There are some other issues with the code (at least from the sandbox) that you will need to work out, but this will at least help get you moving in the right direction.
One part of my application is an image gallery. When the user clicks on an image, I want to put an opaque layer over the image to visualize that it is selected.
When I display the layer, and I click on the image to deselect it, naturally I'm actually clicking on the layer.
Here's the relevant ReactJS code to show what I mean:
{images.map((i, idx) => (
<div key={"cont"+idx} className="container">
<img src={i.images} ref={"img"+idx} />
<div onClick={this.handleIconDeselect} id={"div_"+idx}></div>
</div>
)
)}
I tried to give the img a unique ref (as shown above), but I'm having trouble selecting the correct img.
This is how I try to select the correct image:
handleIconDeselect = (event) => {
var imgref = "icon"+event.target.id.split("_").pop();
this.refs.imgref.click();
}
However, I get the following error message:
TypeError: Cannot read property 'click' of undefined
How can I select the correct image while using unique refs?
Alternatively, if the way I'm trying to achieve this is bad practice (I know you should only use refs when absolutely necessary), what is a better way to do it?
Try use state as here: https://codesandbox.io/s/m4276x643y
Maybe that is not the best way but it give you an rough idea.
import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
const coverStyle = {
position: "fixed",
top: 0,
left: 0,
zIndex: -1,
opacity: 0,
width: "100%",
height: "100%",
background: "#000"
};
const coverStyleShow = {
...coverStyle,
zIndex: 1,
opacity: 1
};
const imgShow = {
zIndex: 10,
position: "relative"
};
const images = [
"https://dummyimage.com/100.png/f10/fff",
"https://dummyimage.com/100.png/f20/fff",
"https://dummyimage.com/100.png/f30/fff",
"https://dummyimage.com/100.png/f40/fff",
"https://dummyimage.com/100.png/f50/fff",
"https://dummyimage.com/100.png/f60/fff",
"https://dummyimage.com/100.png/f70/fff"
];
class App extends Component {
constructor(props) {
super(props);
this.state = {
cover: coverStyle,
img: imgShow,
imgId: null,
imgShow: false
};
}
handleImageClick = (target, idx) => {
// you can do something with this "target"...
this.setState({
cover: coverStyle,
coverShow: coverStyleShow,
imgId: idx,
imgShow: !this.state.imgShow
});
};
render() {
return (
<div>
<Hello name="CodeSandbox" />
<h2>Start editing to see some magic happen {"\u2728"}</h2>
<div>
{images.map((img, idx) => (
<img
key={img}
src={img}
style={idx === this.state.imgId ? this.state.img : null}
onClick={event => this.handleImageClick(event.target, idx)}
alt="dummy img"
/>
))}
</div>
<span
style={this.state.imgShow ? this.state.coverShow : this.state.cover}
/>
</div>
);
}
}
render(<App />, document.getElementById("root"));