Uncaught Error: Cannot find module './undefined' - reactjs

I watched the code multiple times to figure out the problem but couldn't find the solution to this exception thrown at the console. The Product page blanks out.
Product.jsx
import React, { useEffect, useState } from 'react'
import Navbar from '../../Components/Navbar/Navbar'
import Announcment from '../../Components/Announcment/Announcment'
import Newsletter from '../../Components/Newsletter/Newsletter'
import Footer from '../../Components/Footer/Footer'
import styled from 'styled-components'
import './Product.css'
import { Add, Remove } from '#mui/icons-material'
import { useLocation } from 'react-router-dom'
import {publicRequest} from '../../requestMethod';
const Container = styled.div`
`
const Wrapper = styled.div`
padding: 50px;
display: flex;
`
const ImageContainer = styled.div`
flex: 1;
`
const InfoContainer = styled.div`
flex: 1;
padding: 0 50px;
`
const Title = styled.h1`
font-weight: 200;
`
const Desc = styled.p`
margin: 20px 0;
`
const Price = styled.span`
font-weight: 100;
font-size: 40px;
`
const FilterContainer = styled.div`
width: 50%;
display: flex;
justify-content: space-between;
margin: 30px 0;
`
const Filter = styled.div`
display: flex;
align-items: center;
`
const FilterTitle = styled.span`
font-size: 20px;
font-weight: 200;
`
const FilterColor = styled.div`
width: 20px;
height: 20px;
border-radius: 50%;
background-color: ${props => props.color};
margin: 0 5px;
cursor: pointer;
`
const FilterSize = styled.select`
margin-left: 10px;
padding: 5px;
`
const FilterSizeOption = styled.option`
`
const AddContainer = styled.div`
width: 50%;
display: flex;
align-items: center;
justify-content: space-between;
`
const AmountContainer = styled.div`
display: flex;
align-items: center;
font-weight: 700;
`
const Amount = styled.span`
width: 30px;
height: 30px;
border-radius: 10px;
border: 1px solid teal;
display: flex;
justify-content: center;
align-items: center;
margin: 0 5px;
`
const Button = styled.button`
padding: 15px;
border: 3px solid teal;
background-color: white;
cursor: pointer;
font-weight: 500;
&:hover{
background-color: #f8f4f4;
}
`;
const Product = () => {
const location = useLocation();
const Id = location.pathname.split('/')[2];
const [product, setProduct] = useState({});
useEffect(() => {
const getSingleProduct = async () => {
try {
const res = await publicRequest.get(`/products/find/${Id}`);
setProduct(res.data);
} catch (error) {
console.log(error);
}
}
getSingleProduct();
}, [Id]);
return (
<Container>
<Navbar />
<Announcment />
<Wrapper>
<ImageContainer>
<img src={require(`../../Assets/${product.img}`)} alt='' className='productImg2' />
</ImageContainer>
<InfoContainer>
<Title>{product.title}</Title>
<Desc>{product.desc}</Desc>
<Price>$ {product.price}</Price>
<FilterContainer>
<Filter>
<FilterTitle>Color</FilterTitle>
{product.color.map((c, i) => (
<React.Fragment key={i}>
<FilterColor color={c} />
</React.Fragment>
))
}
</Filter>
<Filter>
<FilterTitle>Size</FilterTitle>
<FilterSize>
{product.size.map((s, i) => (
<React.Fragment key={i}>
<FilterSizeOption>{s}</FilterSizeOption>
</React.Fragment>
))
}
</FilterSize>
</Filter>
</FilterContainer>
<AddContainer>
<AmountContainer>
<Remove style={{ cursor: "pointer" }} />
<Amount>1</Amount>
<Add style={{ cursor: "pointer" }} />
</AmountContainer>
<Button>ADD TO CART</Button>
</AddContainer>
</InfoContainer>
</Wrapper>
<Newsletter />
<Footer />
</Container>
);
}
export default Product
requestMethod.js
import axios from 'axios';
const BASE_URL = "http://localhost:5000/api";
const Token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZjI5NmRjY2JmYzNjZTAyNGRhODNlNSIsImlzQWRtaW4iOnRydWUsImlhdCI6MTY2MDEzMzExNiwiZXhwIjoxNjYwMzkyMzE2fQ.TMBcTYhOKhsGTqHgVY6fAGoX9UCc2rC100JwvzoSqhE";
export const publicRequest = axios.create({
baseURL:BASE_URL,
});
export const userRequest = axios.create({
baseURL:BASE_URL,
headers:{token:`Bearer ${Token}`},
});
error
.$:106 Uncaught Error: Cannot find module './undefined'
at webpackContextResolve (.$:106:1)
at webpackContext (.*$:101:1)
at Product (Product.jsx:120:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
The above error occurred in the component:
at Product (http://localhost:3000/static/js/bundle.js:3288:81)
at Routes (http://localhost:3000/static/js/bundle.js:56686:5)
at Router (http://localhost:3000/static/js/bundle.js:56619:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:55428:5)
at App

First time try to check if the product object it's not empty.
Or try every property with product?.title, product?.desc and so on

The issue has been solved by doing these changes.
const Product = () => {
const location = useLocation();
const Id = location.pathname.split('/')[2];
const [product, setProduct] = useState({});
useEffect(() => {
const getSingleProduct = async () => {
try {
const res = await publicRequest.get(`/products/find/${Id}`);
setProduct(res.data);
} catch (error) {
console.log(error);
}
}
getSingleProduct();
}, [Id]);
return (
<Container>
<Navbar />
<Announcment />
<Wrapper>
<ImageContainer>
<img src={product?.img ? require(`../../Assets/${product.img}`) : require('../../Assets/gray-men-shoes-1-free-img.jpg')} alt='' className='productImg2' />
</ImageContainer>
<InfoContainer>
<Title>{product?.title ? product.title : "Gray shoes"}</Title>
<Desc>{product?.desc ? product.desc : "abc"}</Desc>
<Price>$ {product?.price ? product.price : 20}</Price>
<FilterContainer>
<Filter>
<FilterTitle>Color</FilterTitle>
{product.color ? product.color.map((c, i) => (
<FilterColor color={c} key={i} />
))
: <><FilterColor color="black" /></>
}
</Filter>
<Filter>
<FilterTitle>Size</FilterTitle>
<FilterSize>
{product.size ? product.size.map((s, i) => (
<FilterSizeOption key={i}>{s}</FilterSizeOption>
))
: <> <FilterSizeOption >small</FilterSizeOption></>
}
</FilterSize>
</Filter>
</FilterContainer>
<AddContainer>
<AmountContainer>
<Remove style={{ cursor: "pointer" }} />
<Amount>1</Amount>
<Add style={{ cursor: "pointer" }} />
</AmountContainer>
<Button>ADD TO CART</Button>
</AddContainer>
</InfoContainer>
</Wrapper>
<Newsletter />
<Footer />
</Container>
);
}
export default Product

Related

useSelector rendering infinitely

When trying to set value equal to state value using useSelector value is reassigned again and again.
code below console logs quantities infintely
const quantities = useSelector((state) => state.cart.quantity) console.log(quantities)
Cart slice:
import { createSlice } from '#reduxjs/toolkit'
const cartSlice = createSlice({
name: 'cart',
initialState: {
products: [],
quantity: 0,
total: 0,
},
reducers: {
addProduct: (state, action) => {
state.quantity += 1
state.products.push(action.payload)
state.total += action.payload.price * action.payload.quantity
},
},
})
export const { addProduct } = cartSlice.actions
export default cartSlice.reducer
Store.js
import { configureStore, combineReducers } from '#reduxjs/toolkit'
import cartReducer from './cartRedux'
import userReducer from './userRedux'
import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from 'redux-persist'
import storage from 'redux-persist/lib/storage'
const persistConfig = {
key: 'root',
version: 1,
storage,
}
const rootReducer = combineReducers({ user: userReducer, cart: cartReducer })
const persistedReducer = persistReducer(persistConfig, rootReducer)
export const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
})
export let persistor = persistStore(store)
entire component
import { Search, ShoppingCartOutlined } from '#material-ui/icons'
import React from 'react'
import styled from 'styled-components'
import { mobile } from '../responsive'
import { useSelector } from 'react-redux'
import { Link } from 'react-router-dom'
import _ from 'underscore'
const Container = styled.div`
height: 60px;
${mobile({ height: '50px' })}
`
const Wrapper = styled.div`
padding: 10px 20px;
display: flex;
align-items: center;
justify-content: space-between;
${mobile({ padding: '10px 0px' })}
`
const Left = styled.div`
flex: 1;
display: flex;
align-items: center;
`
const Language = styled.span`
font-size: 14px;
cursor: pointer;
${mobile({ display: 'none' })}
`
const SearchContainer = styled.div`
border: 0.5px solid lightgray;
display: flex;
align-items: center;
margin-left: 25px;
padding: 5px;
`
const Input = styled.input`
border: none;
${mobile({ width: '50px' })}
`
const Center = styled.div`
flex: 1;
text-align: center;
`
const Logo = styled.h1`
font-weight: bold;
${mobile({ fontSize: '24px' })}
`
const Right = styled.div`
flex: 1;
display: flex;
align-items: center;
justify-content: flex-end;
${mobile({ flex: 2, justifyContent: 'center' })}
`
const MenuItem = styled.div`
font-size: 14px;
cursor: pointer;
margin-left: 25px;
${mobile({ fontSize: '12px', marginLeft: '10px' })}
`
const Navbar = () => {
const quantities = useSelector((state) => state.cart.quantity)
console.log(quantities)
return (
<Container>
<Wrapper>
<Left>
<Language>EN</Language>
<SearchContainer>
<Input placeholder='Search' />
<Search style={{ color: 'gray', fontSize: 16 }} />
</SearchContainer>
</Left>
<Center>
<Logo>LAMA.</Logo>
</Center>
<Right>
<MenuItem>REGISTER</MenuItem>
<MenuItem>SIGN IN</MenuItem>
<Link to='/cart'>
<MenuItem>
<Badge badgeContent={quantities} color='primary'>
<ShoppingCartOutlined />
</Badge>
</MenuItem>
</Link>
</Right>
</Wrapper>
</Container>
)
}
export default Navbar
Ancestor component
import styled from 'styled-components'
import Announcement from '../components/Announcement'
import Footer from '../components/Footer'
import Navbar from '../components/Navbar'
import Newsletter from '../components/Newsletter'
import { mobile } from '../responsive'
import { useState } from 'react'
import { useEffect } from 'react'
import { publicRequest } from '../requestMethods'
import { Link, useLocation } from 'react-router-dom'
const Container = styled.div``
const Wrapper = styled.div`
padding: 50px;
display: flex;
${mobile({ padding: '10px', flexDirection: 'column' })}
`
const ImgContainer = styled.div`
flex: 1;
`
const Image = styled.img`
width: 100%;
height: 90vh;
object-fit: cover;
${mobile({ height: '40vh' })}
`
const InfoContainer = styled.div`
flex: 1;
padding: 0px 50px;
${mobile({ padding: '10px' })}
`
const Title = styled.h1`
font-weight: 200;
`
const Desc = styled.p`
margin: 20px 0px;
`
const Price = styled.span`
font-weight: 100;
font-size: 40px;
`
const FilterContainer = styled.div`
width: 50%;
margin: 30px 0px;
display: flex;
justify-content: space-between;
${mobile({ width: '100%' })}
`
const Filter = styled.div`
display: flex;
align-items: center;
`
const FilterTitle = styled.span`
font-size: 20px;
font-weight: 200;
`
const FilterColor = styled.div`
width: 20px;
height: 20px;
border-radius: 50%;
background-color: ${(props) => props.color};
margin: 0px 5px;
cursor: pointer;
`
const FilterSize = styled.select`
margin-left: 10px;
padding: 5px;
`
const FilterSizeOption = styled.option``
const AddContainer = styled.div`
width: 50%;
display: flex;
align-items: center;
justify-content: space-between;
${mobile({ width: '100%' })}
`
const AmountContainer = styled.div`
display: flex;
align-items: center;
font-weight: 700;
`
const Amount = styled.span`
width: 30px;
height: 30px;
border-radius: 10px;
border: 1px solid teal;
display: flex;
align-items: center;
justify-content: center;
margin: 0px 5px;
`
const Button = styled.button`
padding: 15px;
border: 2px solid teal;
background-color: white;
cursor: pointer;
font-weight: 500;
&:hover {
background-color: #f8f4f4;
}
`
const Product = () => {
const location = useLocation()
const id = location.pathname.split('/')[2]
const [product, setProduct] = useState({})
const [quantity, setQuantity] = useState(1)
const [color, setColor] = useState('')
const [size, setSize] = useState('')
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get('/product/find/' + id)
setProduct(res.data)
} catch {}
}
getProduct()
})
const handleQuantity = (type) => {
if (type === 'dec') {
quantity > 1 && setQuantity(quantity - 1)
} else {
setQuantity(quantity + 1)
}
}
const handleClick = () => {
//update cart
}
return (
<Container>
<Navbar />
<Announcement />
<Wrapper>
<ImgContainer>
<Image src={product.img} />
</ImgContainer>
<InfoContainer>
<Title>{product.title}</Title>
<Desc>{product.desc}</Desc>
<Price>{product.Price}</Price>
<FilterContainer>
<Filter>
<FilterTitle>Color</FilterTitle>
{product.color?.map((c) => (
<FilterColor
color={c}
key={c}
onClick={() => {
setColor(c)
}}
/>
))}
</Filter>
<Filter>
<FilterTitle>Size</FilterTitle>
<FilterSize>
{product.size?.map((s) => (
<FilterSizeOption
key={s}
onChange={(e) => {
setSize(e.target.value)
}}
>
{s}
</FilterSizeOption>
))}
</FilterSize>
</Filter>
</FilterContainer>
<AddContainer>
<AmountContainer>
<Remove onClick={() => handleQuantity('dec')} />
<Amount>{quantity}</Amount>
<Add onClick={() => handleQuantity('inc')} />
</AmountContainer>
<Button onClick={handleClick}>ADD TO CART</Button>
</AddContainer>
</InfoContainer>
</Wrapper>
<Newsletter />
<Footer />
</Container>
)
}
export default Product
I am currently following an online tutorialenter code here but when he writes the same code it console.logs only once.
I even tried copy pasting his code still my code returns logs infinitely.
I just copied the ancestor component from the tutorial video github and it solved the problem but I don't know what was actually causing it if anyone can help
correct ancestor component
import styled from 'styled-components'
import Announcement from '../components/Announcement'
import Footer from '../components/Footer'
import Navbar from '../components/Navbar'
import Newsletter from '../components/Newsletter'
import { mobile } from '../responsive'
import { useLocation } from 'react-router-dom'
import { useEffect, useState } from 'react'
import { publicRequest } from '../requestMethods'
import { addProduct } from '../redux/cartRedux'
import { useDispatch } from 'react-redux'
const Container = styled.div``
const Wrapper = styled.div`
padding: 50px;
display: flex;
${mobile({ padding: '10px', flexDirection: 'column' })}
`
const ImgContainer = styled.div`
flex: 1;
`
const Image = styled.img`
width: 100%;
height: 90vh;
object-fit: cover;
${mobile({ height: '40vh' })}
`
const InfoContainer = styled.div`
flex: 1;
padding: 0px 50px;
${mobile({ padding: '10px' })}
`
const Title = styled.h1`
font-weight: 200;
`
const Desc = styled.p`
margin: 20px 0px;
`
const Price = styled.span`
font-weight: 100;
font-size: 40px;
`
const FilterContainer = styled.div`
width: 50%;
margin: 30px 0px;
display: flex;
justify-content: space-between;
${mobile({ width: '100%' })}
`
const Filter = styled.div`
display: flex;
align-items: center;
`
const FilterTitle = styled.span`
font-size: 20px;
font-weight: 200;
`
const FilterColor = styled.div`
width: 20px;
height: 20px;
border-radius: 50%;
background-color: ${(props) => props.color};
margin: 0px 5px;
cursor: pointer;
`
const FilterSize = styled.select`
margin-left: 10px;
padding: 5px;
`
const FilterSizeOption = styled.option``
const AddContainer = styled.div`
width: 50%;
display: flex;
align-items: center;
justify-content: space-between;
${mobile({ width: '100%' })}
`
const AmountContainer = styled.div`
display: flex;
align-items: center;
font-weight: 700;
`
const Amount = styled.span`
width: 30px;
height: 30px;
border-radius: 10px;
border: 1px solid teal;
display: flex;
align-items: center;
justify-content: center;
margin: 0px 5px;
`
const Button = styled.button`
padding: 15px;
border: 2px solid teal;
background-color: white;
cursor: pointer;
font-weight: 500;
&:hover {
background-color: #f8f4f4;
}
`
const Product = () => {
const location = useLocation()
const id = location.pathname.split('/')[2]
const [product, setProduct] = useState({})
const [quantity, setQuantity] = useState(1)
const [color, setColor] = useState('')
const [size, setSize] = useState('')
const dispatch = useDispatch()
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get('/product/find/' + id)
setProduct(res.data)
} catch {}
}
getProduct()
}, [id])
const handleQuantity = (type) => {
if (type === 'dec') {
quantity > 1 && setQuantity(quantity - 1)
} else {
setQuantity(quantity + 1)
}
}
const handleClick = () => {
dispatch(addProduct({ ...product, quantity, color, size }))
}
return (
<Container>
<Navbar />
<Announcement />
<Wrapper>
<ImgContainer>
<Image src={product.img} />
</ImgContainer>
<InfoContainer>
<Title>{product.title}</Title>
<Desc>{product.desc}</Desc>
<Price>$ {product.price}</Price>
<FilterContainer>
<Filter>
<FilterTitle>Color</FilterTitle>
{product.color?.map((c) => (
<FilterColor color={c} key={c} onClick={() => setColor(c)} />
))}
</Filter>
<Filter>
<FilterTitle>Size</FilterTitle>
<FilterSize onChange={(e) => setSize(e.target.value)}>
{product.size?.map((s) => (
<FilterSizeOption key={s}>{s}</FilterSizeOption>
))}
</FilterSize>
</Filter>
</FilterContainer>
<AddContainer>
<AmountContainer>
<Remove onClick={() => handleQuantity('dec')} />
<Amount>{quantity}</Amount>
<Add onClick={() => handleQuantity('inc')} />
</AmountContainer>
<Button onClick={handleClick}>ADD TO CART</Button>
</AddContainer>
</InfoContainer>
</Wrapper>
<Newsletter />
<Footer />
</Container>
)
}
export default Product

In React, how to setState a Data by using hook useState?

I am just getting started learning React Functional component and styled- component. I tried to setState detailePageData
const const [marketPriceData, setMarketPriceData] = useState([]);
and I tried to set up the marketPriceData by using JSON file.
useEffect(() => {
fetch(`/data/detailPageData.json`)
.then(res => res.json())
.then(data => setMarketPriceData(data.result.order_history));
}, []);
When I console.log marketPriceData. I got this
In here, I only need the price in each array. So, when I console.log(marketPriceData[0].price); I got 378000 what I expected.
Here is my main question, I only need each array price such as; 378000,341000,388000, etc.
I think I have to edit this part
useEffect(() => {
fetch(`/data/detailPageData.json`)
.then(res => res.json())
.then(data => setMarketPriceData(data.result.order_history));
}, []);
First, I think "Can I use foreach method? or for loop..?" I am not sure how to setup the logic to store the setMarketPriceData. Could you please help me with how to get the price what I expected?
Just in case, I will leave the whole code,
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { FaRegArrowAltCircleDown } from 'react-icons/fa';
import { Line } from 'react-chartjs-2';
import { Modal } from './components/Modal';
import TransitionHistoryModalStyling from '../ProductDetail/components/TransitionHistoryModalStyling';
import DropDownMenu from '../ProductDetail/components/DropDownMenu';
const options = {
scales: {
y: {
beginAtZero: true,
},
},
};
export default function MarketPrice() {
const [showModal, setShowModal] = useState(false);
const [marketPriceData, setMarketPriceData] = useState([]);
// https://github.com/reactchartjs/react-chartjs-2/blob/master/example/src/charts/Line.js
const data = {
labels: ['1', '2', '3', '4', '5', '6'],
datasets: [
{
label: 'MarketPrice',
data: marketPriceData,
fill: false,
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgba(255, 99, 132, 0.2)',
},
],
};
// useEffect(() => {
// let i = 1;
// if (i < detailPageData.order_history.length) {
// setMarketPriceData(detailPageData.order_history[i].price);
// }
// },[]);
const [detailPageData, setDetailPageData] = useState([]);
useEffect(() => {
fetch(`/data/detailPageData.json`)
.then(res => res.json())
.then(data => setDetailPageData(data.result));
}, []);
useEffect(() => {
fetch(`/data/detailPageData.json`)
.then(res => res.json())
.then(data => setMarketPriceData(data.result.order_history));
}, []);
console.log(marketPriceData);
console.log(marketPriceData[0].price);
// console.log(detailPageData.market_price[0].sizes[0].size);
// console.log(detailPageData.order_history);
// console.log(detailPageData.order_history.length);
// console.log(detailPageData.order_history[0].price);
// console.log(detailPageData.order_history.price);
const [currentMenuIndex, setCurrentMenuIndex] = useState(1);
const handleSelectedMenu = tabIndex => {
setCurrentMenuIndex(tabIndex);
};
const openModal = () => {
setShowModal(prev => !prev);
};
return (
<MarketPriceWrapper>
<TitleWrapper>
<MarketPriceTitle>시세</MarketPriceTitle>
<ShowAllSizes>
{/* <AllSize>230</AllSize>
<FaRegArrowAltCircleDown /> */}
<DropDownMenu className={DropDownMenu} />
</ShowAllSizes>
</TitleWrapper>
<SalesGraphWrapper>
<Line data={data} options={options} />
</SalesGraphWrapper>
<ButtonsWrapper>
<Button
isActive={currentMenuIndex === 1}
onClick={() => handleSelectedMenu(1)}
>
체결 거래
</Button>
<Button
isActive={currentMenuIndex === 2}
onClick={() => handleSelectedMenu(2)}
>
판매 입찰
</Button>
<Button
isActive={currentMenuIndex === 3}
onClick={() => handleSelectedMenu(3)}
>
구매 입찰
</Button>
</ButtonsWrapper>
<TableWrapper>
<TableColumnSetting>
<SizeName>사이즈</SizeName>
<PriceName>거래가</PriceName>
<DateName>거래일</DateName>
</TableColumnSetting>
<RowSection>
{/* {detailPageData.market_price &&
detailPageData.market_price.map(price => {
return console.log(price.sizes[0]);
<Size key={price.id}>
<Size>{price.sizes[price.id].size}</Size>
<Price>{price.sizes[price.id].avg_price}</Price>
<Date>{price.date}</Date>
</Size>
})} */}
<Size />
<Price>24,000원</Price>
<Date>99/11/17</Date>
</RowSection>
<RowSection>
<Size />
<Price>24,000원</Price>
<Date>99/11/17</Date>
</RowSection>
<RowSection>
<Size />
<Price>24,000원</Price>
<Date>99/11/17</Date>
</RowSection>
<RowSection>
<Size />
<Price>24,000원</Price>
<Date>99/11/17</Date>
</RowSection>
<RowSection>
<Size />
<Price>24,000원</Price>
<Date>99/11/17</Date>
</RowSection>
<OrderHistoryButton onClick={openModal}>
체결 내역 더보기
</OrderHistoryButton>
<Modal showModal={showModal} setShowModal={setShowModal}>
<TransitionHistoryModalStyling
detailPageDataMarket={detailPageData}
/>
</Modal>
</TableWrapper>
</MarketPriceWrapper>
);
}
const MarketPriceWrapper = styled.div`
width: 550px;
margin-top: 40px;
padding-left: 40px;
`;
const TitleWrapper = styled.div`
display: flex;
padding-top: 19px;
padding-bottom: 12px;
border-bottom: 1px solid #ebebeb;
`;
const SalesGraphWrapper = styled.div``;
const MarketPriceTitle = styled.span`
padding-top: 4px;
display: inline-block;
line-height: 16px;
font-weight: bold;
color: #222;
`;
const ShowAllSizes = styled.div`
margin-left: 370px;
`;
const AllSize = styled.span`
display: inline-block;
margin-right: 5px;
margin-left: 350px;
font-size: 18px;
`;
const ButtonsWrapper = styled.div`
display: flex;
justify-content: space-evenly;
margin-top: 40px;
border-radius: 10px;
background-color: #f4f4f4;
`;
const Button = styled.button`
display: block;
margin: 2px;
line-height: 16px;
padding: 7px 0 9px;
width: 400px;
font-size: 13px;
text-align: center;
border-radius: 8px;
border: none;
background-color: ${props => (props.isActive ? '#ffff' : '#f4f4f4')};
color: rgba(34, 34, 34, 0.8);
`;
const TableWrapper = styled.div`
margin-top: 40px;
`;
const TableColumnSetting = styled.div`
border-bottom: 1px solid #ebebeb;
padding-bottom: 9px;
text-align: right;
`;
const SizeName = styled.span`
display: inline-block;
margin-right: 250px;
font-size: 12px;
color: rgba(34, 34, 34, 0.5);
font-weight: 400;
`;
const PriceName = styled.span`
display: inline-block;
margin-right: 150px;
font-size: 12px;
color: rgba(34, 34, 34, 0.5);
font-weight: 400;
`;
const DateName = styled.span`
display: inline-block;
font-size: 12px;
color: rgba(34, 34, 34, 0.5);
font-weight: 400;
`;
const RowSection = styled.div`
margin-top: 4px;
text-align: right;
`;
const Size = styled.span`
display: inline-block;
margin-right: 240px;
color: #222;
font-size: 12px;
`;
const Price = styled.span`
display: inline-block;
margin-right: 130px;
color: #222;
font-size: 12px;
`;
const Date = styled.span`
display: inline-block;
color: #222;
font-size: 12px;
`;
const OrderHistoryButton = styled.button`
border: 1px solid #d3d3d3;
margin-top: 40px;
background-color: #ffffff;
color: rgba(34, 34, 34, 0.8);
font-weight: 400;
padding: 0 18px;
width: 500px;
height: 42px;
border-radius: 12px;
font-size: 14px;
`;
const const [marketPriceData, setMarketPriceData] = useState([]);
useEffect(() => {
fetch(`/data/detailPageData.json`)
.then(res => res.json())
.then(data => setMarketPriceData(data.result.order_history.map(item => item.price));
}, []);
maybe you can use map in your object data result.
data.result.order_history.map((item)=>{
return item.price
}
That will only get de price property in in your array.
setMarketPriceData(data.result.order_history.map((item)=>{
return item.price
})

Styled-components: Styles are not applied when trying to style already styled component

I'm trying to style my component which was styled already. But styles in the new rules are not applied in output CSS.
Can I style component that I already styled?
Thanks you in advance for your help.
EDIT: Add rest of LanugageChooser definition
// COMPONENT THAT I'M TRYING TO STYLE
const LanguageChooser = () => {
const Container = styled.div`
display: flex;
align-items: center;
height: 36px;
& > div:not(:last-child) {
margin-right: 5px;
}
`;
return (
<Container>
<Flag { ...languages.pl }/>
<Flag { ...languages.en }/>
</Container>
)
}
const Flag = ({ flag, language }) => {
const { i18n } = useTranslation();
const Button = styled.div`
cursor: pointer;
font-size: 24px;
transition: .2s all;
&:hover {
font-size: 36px;
}
`;
return (
<Button onClick={ () => i18n.changeLanguage(language) }>{ flag }</Button>
)
}
// TRYING ADD MARGIN LEFT, BUT THERE IS NO RESULT.
// ANY OTHER CSS PROPERTY ARE NOT APPLYING
const Navbar = ({ color }) => {
...
const StyledLanguageChooser = styled(LanguageChooser)`
margin-left: auto;
`;
const Nav = styled.nav`
display: flex;
align-content:center;
background: ${ color };
padding: 2px 3px;
`;
return (
<Nav className="navbar">
<StyledNavLink to="/home">...</StyledNavLink>
<StyledNavLink to="/maps">...</StyledNavLink>
<StyledNavLink to="/charts">...</StyledNavLink>
<StyledLanguageChooser/>
</Nav>
)
}
First, move the styled component outside of function scope or your style will reset on every render and you will get heavy performance issues.
Secondly, in order to apply styles, you need to pass className property.
See Styling normal React components
If you use the styled(MyComponent) notation and MyComponent does not render the passed-in className prop, then no styles will be applied.
const Container = styled.div`
display: flex;
align-items: center;
height: 36px;
& > div:not(:last-child) {
margin-right: 5px;
}
`;
const LanguageChooser = ({ className }) => {
return (
<Container className={className}>
<Flag {...languages.pl} />
<Flag {...languages.en} />
</Container>
);
};
const Button = styled.div`
cursor: pointer;
font-size: 24px;
transition: 0.2s all;
&:hover {
font-size: 36px;
}
`;
const Flag = ({ flag, language }) => {
const { i18n } = useTranslation();
return <Button onClick={() => i18n.changeLanguage(language)}>{flag}</Button>;
};

React Context API returns undefined

I'm quite new to React, and i'm trying to make a ToDoList. I have a Modal with a submit button that when pressed should add a ToDoItem. But since i didn't want to prop drill my way through this i wanted to use the Context API. The Context API confuses me quite a bit, maybe i'm just a moron, but i have a hard time understanding why i have to make a hook and pass that as the value in the provider. I thought that in the ToDoContext that i already defined the default value as a empty array, so i just did it again.
In the console at line 62, which is my initial render it says that it's undefined, after the pressing the Add ToDo I get the same message.
App.jsx
import React, { useState } from "react";
import { render } from "react-dom";
import { ThemeProvider } from "emotion-theming";
import { defaultTheme } from "./theme";
import { Global, css } from "#emotion/core";
import Header from "./components/Header";
import ToDoList from "./components/ToDoList";
import AddBtn from "./components/AddBtn";
import ToDoContext from "./ToDoContext";
const App = () => {
const [toDoItems] = useState([]);
return (
<>
{/*Global styling*/}
<Global
styles={css`
* {
margin: 0;
padding: 0;
box-sizing: border-box;
list-style: none;
text-decoration: none;
}
`}
/>
{/*App render start from here*/}
<ThemeProvider theme={defaultTheme}>
<ToDoContext.Provider value={toDoItems}>
<Header />
<main>
<ToDoList />
<AddBtn />
</main>
</ToDoContext.Provider>
</ThemeProvider>
</>
);
};
render(<App />, document.getElementById("root"));
ToDoContext.jsx
import { createContext } from "react";
const ToDoContext = createContext([[], () => {}]);
export default ToDoContext;
AddBtn.jsx
import React, { useState, useContext } from "react";
import { css } from "emotion";
import Modal from "../Modal";
import ToDoContext from "../ToDoContext";
const BtnStyle = css`
position: fixed;
bottom: 0;
right: 0;
cursor: pointer;
display: block;
font-size: 7rem;
`;
const ModalDiv = css`
position: fixed;
left: 50%;
background-color: #e6e6e6;
width: 60%;
padding: 20px 20px 100px 20px;
display: flex;
flex-direction: column;
align-items: center;
max-width: 400px;
height: 50%;
transform: translate(-50%, -50%);
border-radius: 20px;
top: 50%;
`;
const textareaStyle = css`
resize: none;
width: 100%;
height: 200px;
font-size: 1.25rem;
padding: 5px 10px;
`;
const timeStyle = css`
font-size: 3rem;
display: block;
`;
const modalSubmit = css`
width: 100%;
font-size: 3rem;
cursor: pointer;
margin-top: auto;
`;
const Label = css`
font-size: 2rem;
text-align: center;
display: inline-block;
margin-bottom: 50px;
`;
const AddBtn = () => {
const [showModal, setShowModal] = useState(true);
const [time, setTime] = useState("01:00");
const [toDoItems, setToDoItems] = useContext(ToDoContext);
console.log(toDoItems);
return (
<>
<div className={BtnStyle} onClick={() => setShowModal(!showModal)}>
<ion-icon name="add-circle-outline"></ion-icon>
</div>
{showModal ? (
<Modal>
<div className={ModalDiv}>
<div>
<label className={Label} htmlFor="time">
Time
<input
className={timeStyle}
type="time"
name="time"
value={time}
onChange={(e) => setTime(e.target.value)}
/>
</label>
</div>
<label className={Label} htmlFor="desc">
Description
<textarea
className={textareaStyle}
name="desc"
placeholder={`Notify yourself this message in ${time}`}
></textarea>
</label>
<button
className={modalSubmit}
onClick={() => {
setToDoItems(
toDoItems.push({
time,
})
);
}}
>
Add ToDo
</button>
</div>
</Modal>
) : null}
</>
);
};
export default AddBtn;
There are few issues in your code to fix:
useState returns a value and a setter. With this line of code, const [toDoItems] = useState([]);, you are just passing an empty array to your context.
So do this:
const toDoItems = useState([]);
In your ToDoContext.js, just pass an empty array as argument (initial value)
const ToDoContext = createContext([]);
Working copy of your code is here. (see console logs)
Also, I noticed that you are pushing the todo in setTodoItems in AddBtn.js.
Don't do this:
onClick={() => {
setToDoItems(
toDoItems.push({
time
})
);
}}
Do this:
onClick={() => {
setToDoItems(
toDoItems.concat([
{
time
}
])
);
}}

React styled components with themeContext

I have the following React Header component in which I'm trying to get a theme value from the ThemeContext.Consumer and pass it into my NavListItem. It's currently working (sort of) but I'd like to only pass it once and have it applied globally. Instead of having to write theme={theme.typography.navigation} each time I use the styled component?
import React from "react"
import { Link } from "gatsby"
import PropTypes from "prop-types"
import styled from "styled-components"
import ThemeContext from "../context/ThemeContext"
const Main = styled.header`
height: 70px;
background-color: white;
position: fixed;
width: 100%;
left: 0;
`
const NavWrapper = styled.div`
position: relative;
`
const NavListLeft = styled.ul`
color: black;
position: absolute;
top: 25px;
left: 40px;
list-style: none;
margin: 0;
padding: 0;
`
const NavListItem = styled.li`
display: inline-block;
margin: 0 10px;
font-family: ${props => props.theme};
font-size: 16px;
`
const Header = ({ siteTitle }) => (
<ThemeContext.Consumer>
{theme => (
<Main>
<NavWrapper>
<NavListLeft>
<NavListItem theme={theme.typography.navigation}>
<Link style={{color: 'black'}}>Women</Link>
</NavListItem>
<NavListItem theme={theme.typography.navigation}>Men</NavListItem>
<NavListItem theme={theme.typography.navigation}>Designers</NavListItem>
<NavListItem theme={theme.typography.navigation}>Collection</NavListItem>
<NavListItem theme={theme.typography.navigation}>Sale</NavListItem>
</NavListLeft>
</NavWrapper>
</Main>
)}
</ThemeContext.Consumer>
)
Header.propTypes = {
siteTitle: PropTypes.string,
}
Header.defaultProps = {
siteTitle: ``,
}
export default Header
You could create a NavListItem that consumes your theme.
const ThemedNavListItem = styled.li`
display: inline-block;
margin: 0 10px;
font-family: ${props => props.theme.typography.navigation};
font-size: 16px;
`
const NavListItem = props => (
<ThemeContext.Consumer>
{theme => <ThemedNavListItem {...props} theme={theme} />}
</ThemeContext.Consumer>
);
const Header = ({ siteTitle }) => (
<Main>
<NavWrapper>
<NavListLeft>
<NavListItem>
<Link style={{color: 'black'}}>Women</Link>
</NavListItem>
<NavListItem>Men</NavListItem>
<NavListItem>Designers</NavListItem>
<NavListItem>Collection</NavListItem>
<NavListItem>Sale</NavListItem>
</NavListLeft>
</NavWrapper>
</Main>
);
A simpler solution using styled-components ThemeProvider.
A helper component for theming. Injects the theme into all styled
components anywhere beneath it in the component tree, via the context
API.
const NavListItem = styled.li`
display: inline-block;
margin: 0 10px;
font-family: ${props => props.theme.typography.navigation};
font-size: 16px;
`
const Header = ({ siteTitle }) => (
<ThemeProvider theme={theme}>
<Main>
<NavWrapper>
<NavListLeft>
<NavListItem>
<Link style={{color: 'black'}}>Women</Link>
</NavListItem>
<NavListItem>Men</NavListItem>
<NavListItem>Designers</NavListItem>
<NavListItem>Collection</NavListItem>
<NavListItem>Sale</NavListItem>
</NavListLeft>
</NavWrapper>
</Main>
</ThemeProvider>
);

Resources