Attempting to place data from an API onto a modal in React - javascript

I'm attempting to put data that I'm getting from an API onto a modal that will appear whenever a button is clicked.
How is this done? I'm able to use the data from the API without the modal, so I know it's not an issue with the syntax of my componentDidMount(). Not sure what the issue is and how it can be resolved.
import React from 'react';
import './App.css';
import Nav from './Nav';
import Meal from './Meal';
import meals from './Meals';
import Modal1 from './Modal'
function App() {
const mealArr = meals.map(item => <Meal food={item.food} picture={item.picture} type={item.id} />)
return (
<div className="content">
<Nav />
{mealArr}
<Modal1 isOpen={false}/>
</div>
);
}
export default App;
import React from 'react';
import Modal from 'react-modal';
class Modal1 extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
}
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json
})
})
}
render() {
const allItems = this.state.items;
let itemArr = allItems.map(item =>
<div>
<ul>
<li key={item.id}>{item.name}</li>
</ul>
</div>)
return (
<div>
<Modal>
{itemArr}
</Modal>
</div>
)
}
}
export default Modal1;
import React, {Component} from 'react';
import Modal1 from 'react-modal';
class Meal extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: false
}
this.handleClick = this.handleClick.bind(this);
this.turnOff = this.turnOff.bind(this);
}
handleClick() {
this.setState({isOpen: true})
}
turnOff() {
this.setState({isOpen: false})
}
render() {
return (
<div className="meal-container">
<h2>{this.props.type}</h2>
<h1>{this.props.food}</h1>
<img alt="" src={this.props.picture} />
<p className="steps-button" onClick={this.handleClick}>Steps</p>
<Modal1 className="modal-1" isOpen={this.state.isOpen}/>
</div>
)
}
}
export default Meal;

take a look at allItems, it's an empty array before you get the data from the API.
So, for the first render (before component did mount):
const allItems = this.state.items // ----> const allItems = []
mapping through an empty array will not produce any error and return another empty array, but when you map through an empty array, don't expect to have any item or item.name. so the itemArr is not as your expectation and cause the issue with rendering it.
to avoid from this issue, check your allItems to ensure that the data has arrived.
const allItems = this.state.items;
let itemArr = []
if (allItems.length > 0) {
itemArr = allItems.map(item => (
<div>
<ul>
<li key={item.id}>{item.name}</li>
</ul>
</div>
)
}
return (
<div>
<Modal>
{itemArr}
</Modal>
</div>
)

Related

React onClick event in array.map()

Edit: I have included the full code for better clarity
I am not sure if this is possible. I am trying to pass an onClick event via props but the click event does not work.
The parent component looks like this:
import React from 'react'
import { getProductsById } from '../api/get'
import Product from './Product'
import { instanceOf } from 'prop-types'
import { withCookies, Cookies } from 'react-cookie'
class Cart extends React.Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
}
constructor(props) {
super(props)
const { cookies } = props;
this.state = {
prods: cookies.get('uircartprods') || '',
collapsed: true,
total: 0,
}
this.expand = this.expand.bind(this)
this.p = [];
}
componentDidMount() {
this.getCartProducts()
}
handleClick = (o) => {
this.p.push(o.id)
const { cookies } = this.props
cookies.set('uircartprods', this.p.toString(), { path: '/' , sameSite: true})
this.setState({prods: this.p })
console.log('click')
}
getCartProducts = async () => {
let products = []
if (this.state.prods !== '') {
const ts = this.state.prods.split(',')
for (var x = 0; x < ts.length; x++) {
var p = await getProductsById(ts[x])
var importedProducts = JSON.parse(p)
importedProducts.map(product => {
const prod = <Product key={product.id} product={product} handler={() => this.handleClick(product)} />
products.push(prod)
})
}
this.setState({products: products})
}
}
expand(event) {
this.setState({collapsed: !this.state.collapsed})
}
handleCheckout() {
console.log('checkout clicked')
}
render() {
return (
<div className={this.state.collapsed ? 'collapsed' : ''}>
<h6>Your cart</h6>
<p className={this.state.prods.length ? 'hidden' : ''}>Your cart is empty</p>
{this.state.products}
<h6>Total: {this.props.total}</h6>
<button onClick={this.handleCheckout} className={this.state.prods.length ? '' : 'hidden' }>Checkout</button>
<img src="./images/paypal.png" className="paypal" alt="Paypal" />
<a className="minify" onClick={this.expand} alt="My cart"></a>
<span className={this.state.prods.length ? 'pulse' : 'hidden'}>{this.state.prods.length}</span>
</div>
)
}
}
export default withCookies(Cart)
The Product component:
import React from 'react';
class Product extends React.Component {
constructor(props) {
super(props);
this.state = {
showDetails: false,
showModal: false,
cart: []
}
this.imgPath = './images/catalog/'
}
render() {
return (
<div className="Product">
<section>
<img src={this.imgPath + this.props.product.image} />
</section>
<section>
<div>
<h2>{this.props.product.title}</h2>
<h3>{this.props.product.artist}</h3>
<p>Product: {this.props.product.product_type}</p>
<h4>${this.props.product.price}</h4>
<button className="button"
id={this.props.product.id} onClick={this.props.handler}>Add to cart</button>
</div>
</section>
</div>
)
}
}
export default Product
If I log this.props.handler I get undefined. Everything works apart from the click handler, I was wondering if it might have something to with the async function. I am very new to React, there are still some concepts I'm not sure about, so any help is appreciated.
Okay, I see a few issues here.
First, there is no need to call this.handleClick = this.handleClick.bind(this) in the constructor, because you are using an arrow function. Arrow functions do not have a this context, and instead, accessing this inside your function will use the parent this found in the Class.
Secondly, it is wrong to store components in state. Instead, map your importedProducts inside the render function.
Thirdly, the issue with your handler is that this.props.handler doesn't actually call handleClick. You will notice in the definition handler={(product) => this.handleClick} it is returning the function to the caller, but not actually calling the function.
Try this instead.
class Product extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<button className="button" id={this.props.product.id} onClick={this.props.handler}>
Add to cart
</button>
</div>
);
}
}
export default Product;
import Product from './Product'
class Cart extends React.Component {
constructor(props) {
super(props);
}
handleClick = (o) => {
console.log('click');
};
render() {
return (
<div>
{importedProducts.map((product) => {
return <Product key={product.id} product={product} handler={() => this.handleClick(product)} />;
})}
</div>
);
}
}
export default Cart;

Sending API data in Gatsby to be used in Chart.js

I am trying to send API data being called from my index.js to my ChartData.js. index.js is a page and ChartData.js is a component in Gatsby, so to begin with I could not figure out if Gatsby's Link to="" function only work from one page to another or if it can send data from a page to a component.
The issue is when I try to access the sent data from index.js to ChartData.js in the line {props.location.state.companyName} I am getting the error: TypeError: props.location is undefined
I plan to switch out labels: ['x', 'y'] for something like labels: [{props.location.state.companyName}, {props.location.state.symbol} etc. I am not sure if this would be the correct syntax either.
A more detailed explanation here: https://www.youtube.com/watch?v=No9cqzqlKS0&feature=youtu.be
index.js:
import React from "react"
import { Link } from "gatsby"
import axios from "axios"
import "../css/style.css"
import Layout from "../components/layout"
import { symbol } from "prop-types"
import ChartData from "../components/ChartData"
export default class index extends React.Component {
state = {
companyName: "",
previousClose: "",
marketCap: "",
change: "",
symbol: "",
topStocks: [],
Yearweekhigh: "",
Yearweeklow: "",
avgTotalVolume: "",
peRatio: ""
}
componentDidMount() {
const API_KEY = '*******************';
axios.get(`https://cloud.iexapis.com/stable/stock/market/previous?token=${API_KEY}`)
.then(res => {
console.log(res)
const topStocks = res.slice(1);
this.setState({ topStocks })
})
}
clickHandler = (event) => {
if (event.keyCode === 13) {
const query = event.target.value;
const API_KEY = '*******************';
axios.get(`https://cloud.iexapis.com/stable/stock/${query}/quote?token=${API_KEY}`)
.then(res => {
const companyName = res.data['companyName'];
this.setState({ companyName })
const previousClose = res.data['previousClose'];
this.setState({ previousClose })
const marketCap = res.data['marketCap'];
this.setState({ marketCap })
const change = res.data['change'];
this.setState({ change })
const symbol = res.data['symbol'];
this.setState({ symbol })
const Yearweekhigh = res.data['week52High'];
this.setState({ Yearweekhigh })
const Yearweeklow = res.data['week52Low'];
this.setState({ Yearweeklow })
const avgTotalVolume = res.data['avgTotalVolume'];
this.setState({ avgTotalVolume })
const peRatio = res.data['peRatio'];
this.setState({ peRatio })
})
}
}
render() {
return (
<Layout>
<div class = "main-div">
<input type="search" class="main-search" onKeyDown={event => this.clickHandler(event)}/>
<table>
<tr>
<th>Ticker-Symbol</th>
<th>Market Cap</th>
<th>Previous Close</th>
</tr>
<tr>
<td>
<Link to='/details/' state={{
setState: this.state.symbol,
companyName: this.state.companyName,
previousClose: this.state.previousClose,
marketCap: this.state.marketCap,
change: this.state.change,
Yearweekhigh: this.state.Yearweekhigh,
Yearweeklow: this.state.Yearweeklow,
avgTotalVolume: this.state.avgTotalVolume,
peRatio: this.state.peRatio
}}>
{this.state.symbol}</Link>
<Link to='/ChartData/' state={{
setState: this.state.symbol,
companyName: this.state.companyName,
previousClose: this.state.previousClose,
marketCap: this.state.marketCap,
change: this.state.change,
Yearweekhigh: this.state.Yearweekhigh,
Yearweeklow: this.state.Yearweeklow,
avgTotalVolume: this.state.avgTotalVolume,
peRatio: this.state.peRatio
}}></Link>
</td>
<td>{this.state.marketCap}</td>
<td>{this.state.previousClose}</td>
</tr>
</table>
</div>
<div>
{
this.state.topStocks.length && this.state.topStocks.map(stock => (
<h1>{stock.symbol}</h1>
))
}
</div>
<ChartData />
</Layout>
)
}
}
details.js
//import { Link } from "gatsby"
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import Layout from '../components/layout';
import "../css/style.css"
const Details = props => {
const [yourState, setYourState] = useState('');
useEffect(() => {
}, []);
return <Layout>
<div>
<h1 class="details-company-name">{props.location.state.companyName}</h1>
<div class = "details-div">
<div class="details-div-1">
<p>Open {} </p>
<p>High {} </p>
<p>Low {} </p>
<p>52 WK HIGH <h2>{props.location.state.Yearweekhigh}</h2> </p>
<p>52 WK LOW <h2>{props.location.state.Yearweeklow}</h2> </p>
</div>
<div class="details-div-2">
<p>VOLUME</p>
<p>AVG VOL <h2>{props.location.state.avgTotalVolume}</h2> </p>
<p>MKT CAP <h2>{props.location.state.marketCap}</h2></p>
<p>P/E RATIO <h2>{props.location.state.peRatio}</h2></p>
<p>DIV/YIELD</p>
</div>
</div>
</div>
</Layout>;
};
export default Details;
ChartData.js
import React, {useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
const ChartData = props => {
const [yourState, setYourState] = useState('');
const chart = () => {
setYourState({
labels: ['x', 'y'],
datasets: [
{
level: 'level of xyz',
data: [22, 55]
}
]
})
}
useEffect(() => {
chart()
}, [])
return(
<div>
<h1>Hello</h1>
{props.location.state.companyName}
<div>
<Line data={yourState}/>
</div>
</div>
)
}
export default ChartData;
There's a quite a bit going on here that needs clarification. You mention graphql in the title, but there's no graphql in your code.
You are using axios to fetch data at runtime in the componentDidMount lifecycle method, and then setting the result to state.
I assume that once you have that data, all you want to do is pass it to your chart component so that it can render itself on the index page.
Consider the following example which does the same thing; Fetches some data from the Rick & Morty api, sets the results to state, and passes the relevant part of that state via props directly to the <Characters /> component.
From there, the <Characters /> component has everything it needs in order to render. (It has no state, and is not concerned about where the data actually came from).
// index.js
import React from 'react';
import './App.css';
import Characters from './Characters'
const api = "https://rickandmortyapi.com/api/character/";
class IndexPage extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch(api)
.then(res => res.json())
.then(
json => {
console.log(json)
this.setState({
isLoaded: true,
data: json.results
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
render() {
const { error, isLoaded, data } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<Characters data={data} />
);
}
}
}
export default IndexPage;
// Characters.js
import React from 'react';
class Characters extends React.Component {
render() {
return (
<ul>
{this.props.data.map(item => (
<li key={item.id}>
<dl>
<dt>Name:</dt>
<dd>{item.name}</dd>
<dt>Species:</dt>
<dd>{item.species}</dd>
<dt>Status:</dt>
<dd>{item.status}</dd>
</dl>
</li>
))}
</ul>
);
}
}
export default Characters;
Codesandbox Example using functional components and hooks
Gatsby’s <Link> component allows you to link between pages (and does some other stuff like prefetching resources, and can share data between pages). As you are rendering the <ChartData /> component on the index page, this is not required to solve your problem.
Using <Link> with state works because details is a gatsby page. As <ChartData> is not a page, you can't *link* to it.

ReactJS TypeError: Cannot read property 'eventEmitter' of undefined

I'm currently building a ReactJS Weather app where I have a drop-down list with different cities and a container with the information about weather on the selected city. When i fetch the weather data from an API i have a default city and I want to refetch the data when user selects another city in the dropdown list.
I will provide you with the code.
App.jsx class (the main class)
import React, { Component } from "react";
import "./sass/app.scss";
import axios from "axios";
import { Dropdown } from "semantic-ui-react";
import NavigationBar from "./components/NavigationBar";
import WeatherComponent from "./components/WeatherComponent";
import { locationOptions } from "./locations.js";
const WEATHER_KEY = "5f0f0f2a61c0f3f650984fb442f03d86";
class App extends Component {
constructor(props) {
super(props);
this.state = {
cityName: "Pristina",
isLoading: true,
isSelectedLocationOpen: false
};
}
componentDidMount() {
const { cityName } = this.state;
const { eventEmitter } = this.props;
const URL = `http://api.weatherstack.com/current?access_key=${WEATHER_KEY}&query=${cityName}`;
axios
.get(URL)
.then(res => {
return res.data;
})
.then(data => {
this.setState({
isLoading: false,
name: data.location.name,
country: data.location.country,
temperature: data.current.temperature,
weather_descriptions: data.current.weather_descriptions[0],
weather_icons: data.current.weather_icons[0],
observation_time: data.current.observation_time
});
})
.catch(err => {
console.error("Cannot fetch weatcher from API", err);
});
eventEmitter.on("updateLocation", data => {
this.setState({ cityName: data });
});
}
handleChange() {
const { eventEmitter } = this.props;
const { cityName } = this.state;
eventEmitter.emit("updateLocation", cityName);
}
render() {
const {
isLoading,
name,
temperature,
weather_descriptions,
weather_icons,
observation_time,
country
} = this.state;
return (
<div className="main-container">
<div className="first-container">
<div className="wrapper">
{isLoading && <h3>Loading ...</h3>}
<NavigationBar />
{!isLoading && (
<WeatherComponent
className="weather-container"
name={name}
temperature={temperature}
weather_descriptions={weather_descriptions}
weather_icons={weather_icons}
observation_time={observation_time}
country={country}
/>
)}
<Dropdown
placeholder="Select location"
search
selection
defaultValue={this.state.cityName}
options={locationOptions.map(item => {
return {
key: item.key,
value: item.value,
text: item.text
};
})}
onChange={this.handleChange}
value={locationOptions.value}
/>
</div>
</div>
</div>
);
}
}
export default App;
store.js class
import React from "react";
import { EventEmitter } from "events";
export default class Store extends React.Component {
constructor(props) {
super(props);
this.eventEmitter = new EventEmitter();
// Main App State
this.state = {
appName: "Weather App"
};
}
render() {
return React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
...this.state,
eventEmitter: this.eventEmitter
});
});
}
}
WeatherComponent.js
import React from "react";
import "../sass/weather.scss";
import sunnyIcon from "../assets/sunnyicon.png";
import sun from "../assets/sunicon.png";
export default class WeatherComponent extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
// weather_descriptions i have to find a better icon for current weather
render() {
const {
temperature,
weather_descriptions,
observation_time,
name,
country
} = this.props;
return (
<div className="weather-container">
<div className="location-container">
<img src={sunnyIcon} className="logo2" alt="" />
<h1 className="total-weather-report">Today's weather report</h1>
<h1 className="location">{`${name}, ${country}`}</h1>
</div>
<div className="degree-container">
<img src={sunnyIcon} className="weather-logo2" alt="" />
<h2 className="degree-value">{`${temperature}°C`}</h2>
</div>
<div className="info-container">
<h2 className="local-weather-report">Local Weather Report</h2>
<div className="hr"></div>
<img src={sun} className="sun-icon" alt="" />
<h2 className="day">Sunday</h2>
<h2 className="weather-type">{weather_descriptions}</h2>
<h2 className="last-observation">Last observed on:</h2>
<h2 className="observation-time">{observation_time}</h2>
</div>
<div className="weekly-weather"></div>
</div>
);
}
}
When I run the app everything works but when I try to change the city from the dropdown, it crashes and this error pops-up.
The error
EventEmitter is part of the NodeJS API, is not available for browsers.
EDIT:
In App.jsx you have a function called "handleChange", that function should do the same thing you are doing on "componenDidMount" but using the actual value of the Dropdown, you don't need to manually create events.
Hope it helps

"Cannot read property 'map' of undefined" within React, what's wrong here?

Trying to get my head around props so forgive me if its a silly mistake. I am trying to pass all of my data into one variable and pass that out into props (using {item.text} and {item.key}), however, my ".map" isn't picking up anything and there's a bunch of errors, what's wrong with my code?
The problem lays specifically here in this block of code
createList(list) {
return <li>{list.text}</li>
}
render() {
var entries = this.state.list
var finalEntries = entries.props.map(this.createList)
Here is the code in full
import React from "react";
import "./App.css";
import { isTemplateElement } from "#babel/types";
class TodoListt extends React.Component {
state = {};
constructor(props) {
super(props);
this.state = {
userInput: "",
list: [],
};
}
changeUserInput(input) {
this.setState({
userInput: input
})
}
addToList(input) {
let listArray = this.state.list;
listArray.push(input);
var newItem = {
text: listArray,
key: Date.now()
};
this.setState(prevState => {
return {
list: prevState.list.concat(newItem)
};
});
this.setState({
list: listArray
})
}
createList(list) {
return <li>{list.text}</li>
}
render() {
var entries = this.state.list
var finalEntries = entries.props.map(this.createList)
return (
<div className="to-do-list-main">
<input
onChange={(e) => this.changeUserInput(e.target.value)}
value={this.state.userInput}
type="text"
/>
<button onClick={() => this.addToList(this.state.userInput)}>Press me</button>
<ul>
{this.testingSetup()}
</ul>
</div>
);
}
}
export default TodoListt;
You can use the spread operator to add to an existing array. Simply add a new object to the array in the state, and then clear the user input, ready for another item. Based on your code, here's a simple example of adding to a state list (haven't run myself, so just check for syntax errors and such):
import React from "react";
import "./App.css";
import { isTemplateElement } from "#babel/types";
class TodoList extends React.Component {
state = {};
constructor(props) {
super(props);
this.state = {
userInput: "",
list: [],
};
}
changeUserInput(input) {
this.setState({
userInput: input
})
}
addToList() {
const { list, userInput } = this.state;
// Add item to state list using spread operator and clear input
this.setState({
list: [...list, {text:userInput, key: Date.now()}],
userInput: ""
});
}
render() {
return (
<div className="to-do-list-main">
<input
onChange={(e) => this.changeUserInput(e.target.value)}
value={this.state.userInput}
type="text"
/>
<button onClick={() => this.addToList()}>Press me</button>
<hr/>
{/* For each item in the list, render the contents */}
{this.state.list.map(item => (
<div key={item.key}>
<h3>{item.text}</h3>
<p>Time: {item.key}</p>
</div>
))}
</div>
);
}
}
export default TodoList;

Reactjs: How to recognized clicked list

I'm having trouble with my list of buttons. What I'm trying to achieve is simple: click button a, show list of a1 to a3, click button b, show list of b1 to b3. I'm trying to make react to recognize which button is clicked. So far i ended up with nothing, everytime i click a button button a and b will display its children
these are my codes
CategoryContainer
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {getCategory} from '../actions/categoryActions'
import {ShowSubCategory} from '../actions/interactionActions'
import {ShowItemCategory} from '../actions/interactionActions'
import Category from '../components/category'
class CategoryContainer extends Component{
constructor(props){
super(props);
console.log('category props', this.props.categories);
this.state = {
showsubcategory: false,
showitemcategory: false,
selectedsubcat: null,
selecteditemcat: null
}
}
componentWillMount(){
console.log('masuk CDM');
this.props.fetchCategory()
}
toggleSubCategory = (event) => {
console.log('masuk togglesubcategory', event);
this.setState({showsubcategory: !this.state.showsubcategory}, ()=>{
var isOpen = this.state.showsubcategory
this.props.showSubCategory(isOpen)
// if(isOpen){
// console.log('masuk block');
// document.getElementById("subcategorycontainer-" + id).style.display = "block"
//this does not work
// }
// else{
// console.log('masuk none');
// document.getElementById("subcategorycontainer-" + id).style.display = "none"
// }
})
}
render(){
var viewtypequery = window.innerWidth >= 1025 ? "computers" : "mobile"
return(
<Category alphabets={this.state.alph}
categorylist={this.props.categories}
view={viewtypequery}
isFetching={this.props.fetching}
togglesub={this.toggleSubCategory}
showsub={this.state.showsubcategory}
/>
)
}
}
const mapStateToProps = (state) => {
console.log('state mapstate', state);
return{
categories: state.category.categories,
fetching: state.category.isfetching,
error: state.category.error,
showsubcategory: state.interaction.showsubcategory,
showitemcategory: state.interaction.showitemcategory
}
}
const mapDispatchToProps = (dispatch) => {
return{
fetchCategory: () => {
dispatch(getCategory())
},
showSubCategory: (showsubcategory) => {
dispatch(ShowSubCategory(showsubcategory))
},
showItemCategory: (showitemcategory) => {
dispatch(ShowItemCategory(showitemcategory))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(CategoryContainer)
category
import React from 'react'
import {Link} from 'react-router'
import Subcategory from './subcategory'
import BrandContainer from '../containers/brandContainer'
class Category extends React.Component{
constructor(props){
super(props)
}
render(){
console.log('isi ref cuk', this.subcatcontainer);
console.log('props category', this.props);
console.log('from category', this.props.categorylist);
if(this.props.fetching)
return(<div>loading..</div>)
// const showitem = this.props.categorylist.
const categorylist = this.props.categorylist.map((cl, index) => {
var subcategory = cl.children.map(sc => {
return <Subcategory key={sc.id} subcatname={sc.categoryname} subcatchild={sc.children} id={sc.id}/>
})
return(
<div>
<div class="listheader">
<button key={cl.id} id={"category_" + cl.id} class="category listheaderinner" onClick={this.props.togglesub.bind(this, index)}>
{cl.categoryname}
<span class="icon-caret kCaret kCaret-right icon-size-small"></span>
</button>
</div>
<div id={"subcategorycontainer-" + cl.id} class="subcategorycontainer container-fluid">
{subcategory}
</div>
</div>
)
}, this)
switch(this.props.view){
case "mobile":
return(
<div class="category-container">
<BrandContainer />
<div id="sale" class="listheader">
<button class="category listheaderinner">SALE<span class="icon-caret kCaret kCaret-right icon-size-small"></span></button>
</div>
{categorylist}
</div>
)
break;
}
}
}
export default Category
and i found a post on SO suggesting that i should breakdown the array into another component so here is my
subcategory
import React, {Component} from 'react'
import {connect} from 'react-redux'
class Subcategory extends Component{
render(){
console.log('showsub', this.props.showsubcategory);
var displayquery = this.props.showsubcategory ? "sublistitem listheaderinner ke-btn-transparent" : "sublistitem-hide listheaderinner ke-btn-transparent"
console.log(displayquery);
return(
<div>
<button key={this.props.id} id={"subcategory_" + this.props.id} class={displayquery}>
{this.props.subcatname}
<span class="icon-caret kCaret kCaret-right icon-size-small"></span>
</button>
<div class="itemcategorycontainer container-fluid">
</div>
</div>
// <li class="sublistitem categorylistitem" key={sc.id}><Link to="/category">{sc.categoryname}</Link></li>
)
}
}
const mapStateToProps = (state) => {
return{
showsubcategory: state.interaction.showsubcategory
}
}
export default connect(mapStateToProps)(Subcategory)
I really need help, I've been googling solutions even posted here for days and ended up with nothing

Categories

Resources