I am trying to iterate through an array of objects to display all items of a certain name. For some reason my this.props.list.items cannot be read. Any help would be greatly appreciated.
The code for item.js
import React from "react";
class Item extends React.Component{
render() {
return(
<div>{this.props.list.items}</div>
)
}
}
export default Item
The code for horizontalscroll.js
import React from 'react';
import ScrollMenu from 'react-horizontal-scrolling-menu';
import './horizontalscroll.css';
import Item from './Item';
// list of items
const list = [
{
name: "Brands",
items: ["1", "2", "3"]
},
{
name: "Films",
items: ["f1", "f2", "f3"]
},
{
name: "Holiday Destination",
items: ["f1", "f2", "f3"]
}
];
// One item component
// selected prop will be passed
const MenuItem = ({ text, selected }) => {
return (
<div
className="menu-item"
>
{text}
</div>
);
};
// All items component
// Important! add unique key
export const Menu = (list) => list.map(el => {
const { name } = el;
return (
<MenuItem
text={name}
key={name}
/>
);
});
const Arrow = ({ text, className }) => {
return (
<div
className={className}
>{text}</div>
);
};
const ArrowLeft = Arrow({ text: '<', className: 'arrow-prev' });
const ArrowRight = Arrow({ text: '>', className: 'arrow-next' });
class HorizantScroller extends React.Component {
state = {
selected: 0
};
onSelect = key => {
this.setState({ selected: key });
}
render() {
const { selected } = this.state;
// Create menu from items
const menu = Menu(list, selected);
return (
<div className="HorizantScroller">
<ScrollMenu
data={menu}
arrowLeft={ArrowLeft}
arrowRight={ArrowRight}
selected={selected}
onSelect={this.onSelect}
/>
<div>{this.props.items.map((item) => {
return <Item item={item}/>
})}
</div>
</div>
);
}
}
export default HorizantScroller;
Inside Item, you should access it like this
<div>{this.props.item}</div>
Because when rendering Item, you did <Item item={item}/>
Related
import { Fragment, useState } from "react";
import Select from 'react-select';
let items = [
{
item: 1,
name: "tv"
},
{
item: 2,
name: "PC"
}
]
const Home = () => {
const [selectedValue, setSelectedValue] = useState(6)
const handleChange = obj => {
setSelectedValue(obj.item)
}
return (
<Fragment>
<div>Home page</div>
<p>Test React Select...</p>
<Select
value={items.find(x => x.item === selectedValue)}
options={items}
onChange={handleChange}
/>
<p>selected Value:...</p>
{selectedValue}
</Fragment>
)
}
export default Home;
you can pass the mapped array to "options" property:
options={items.map(({item, name}) => ({value: name, label: item}))}
I'm trying to implement react horizontal scroll using React horizontal scrolling menu library, but when I use this component in my react app, it shows nothing and I am also not getting any error message.
Here is the code of that component:
import React, { useState } from "react";
import { ScrollMenu } from "react-horizontal-scrolling-menu";
// list of items
const list = [
{ name: "item1" },
{ name: "item2" },
{ name: "item3" },
{ name: "item4" },
{ name: "item5" },
{ name: "item6" },
{ name: "item7" },
{ name: "item8" },
{ name: "item9" },
];
// One item component
// selected prop will be passed
const MenuItem = ({ text, selected }) => {
return <div className="menu-item text-black">{text}</div>;
};
// All items component
// Important! add unique key
export const Menu = (list) =>
list.map((el) => {
const { name } = el;
return <MenuItem text={name} key={name} />;
});
const Arrow = ({ text, className }) => {
return <div className={className}>{text}</div>;
};
const ArrowLeft = Arrow({ text: "<", className: "arrow-prev" });
const ArrowRight = Arrow({ text: ">", className: "arrow-next" });
const AvataaarsScroll = () => {
const [selected, setSelected] = useState(0);
const onSelect = (key) => {
setSelected(key);
};
// Create menu from items
const menu = Menu(list, selected);
return (
<div className="App">
<ScrollMenu
data={menu}
arrowLeft={ArrowLeft}
arrowRight={ArrowRight}
selected={selected}
onSelect={onSelect}
/>
</div>
);
};
export default AvataaarsScroll;
Anyone please help me with this.
You are sending the menu items to the ScrollMenu through the property named data, but you need to send them as children elements:
<div className="App">
<ScrollMenu
arrowLeft={ArrowLeft}
arrowRight={ArrowRight}
selected={selected}
onSelect={onSelect}
>
{menu}
</ScrollMenu>
</div>
...or...
<ScrollMenu
arrowLeft={ArrowLeft}
arrowRight={ArrowRight}
selected={selected}
onSelect={onSelect}
children={menu}
/>
I have a list of buttons and I'm trying to toggle the classname when one is clicked. So that only when I click on a specific button is highlighted. I have a TagList component that looks like this:
const Tags = ({tags, onTagClick}) => {
return (
<div className="tags-container">
{ tags.map(tag => {
return (
<span
key={tag.name}
className="tag"
onClick={() => onTagClick(tag)}
>
{tag.name} | {tag.numberOfCourses}
</span>
)
})
}
</div>
)
}
And this is found in the parent component:
onTagClick = (tag) => {
this.filterCourses(tag)
}
render() {
const { tags, courses } = this.state
return (
<div>
<h1> Course Catalog Component</h1>
<Tags tags={tags} onTagClick={this.onTagClick} />
<Courses courses={courses} />
</div>
)
}
I know how I could toggle the class for a single button but I'm a little confused when it comes to a list of buttons. How can I toggle one specifically from a list of buttons? Am I going to need a seperate Tag component and add state to that one component?
EDIT:
This is what my state currently looks like:
constructor(props) {
super(props)
this.state = {
tags: this.sortedTags(),
courses: courses
}
}
And this is what filterCourses looks like:
filterCourses = (tag) => {
this.setState({
courses: courses.filter(course => course.tags.includes(tag.name))
})
}
To start, you would want to give each tag object you're working with a selected property. That will make it easier for you to toggle the class. During the rendering of that markup.
Here is the working sandbox: https://codesandbox.io/s/stupefied-cartwright-6zpxk
Tags.js
import React from "react";
const Tags = ({ tags, onTagClick }) => {
return (
<div className="tags-container">
{tags.map(tag => {
return (
<div
key={tag.name}
className={tag.selected ? "tag selected" : "tag"}
onClick={() => onTagClick(tag)}
>
{tag.name} | {tag.numberOfCourses}
</div>
);
})}
</div>
);
};
export default Tags;
Then in the Parent component, we simply toggle the selected prop (True/False) when the tag is clicked. That will update the tags-array and it gets passed back down to the Child-component which now has the new selected values.
Parent Component
import React from "react";
import ReactDOM from "react-dom";
import Tags from "./Tags";
import Courses from "./Courses";
import "./styles.css";
class App extends React.Component {
state = {
tags: [
{ id: 1, name: "math", numberOfCourses: 2, selected: false },
{ id: 2, name: "english", numberOfCourses: 2, selected: false },
{ id: 3, name: "engineering", numberOfCourses: 2, selected: false }
],
courses: [
{ name: "Math1a", tag: "math" },
{ name: "Math2a", tag: "math" },
{ name: "English100", tag: "english" },
{ name: "English200", tag: "english" },
{ name: "Engineering101", tag: "engineering" }
],
sortedCourses: []
};
onTagClick = tag => {
const tagsClone = JSON.parse(JSON.stringify(this.state.tags));
let foundIndex = tagsClone.findIndex(tagClone => tagClone.id == tag.id);
tagsClone[foundIndex].selected = !tagsClone[foundIndex].selected;
this.setState(
{
tags: tagsClone
},
() => this.filterCourses()
);
};
filterCourses = () => {
const { tags, courses } = this.state;
const selectedTags = tags.filter(tag => tag.selected).map(tag => tag.name);
const resortedCourses = courses.filter(course => {
return selectedTags.includes(course.tag);
});
this.setState({
sortedCourses: resortedCourses
});
};
render() {
const { tags, sortedCourses, courses } = this.state;
return (
<div>
<h1> Course Catalog Component</h1>
<Tags tags={tags} onTagClick={this.onTagClick} />
<Courses courses={!sortedCourses.length ? courses : sortedCourses} />
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I am new to react and I've been trying to achieve a function that I am not sure of, I have a component that renders JSON file and shows products named 'product list', another component named 'person' which is used to show product items, both are working fine, but the third component called menucat includes the scrolling menu from https://www.npmjs.com/package/react-horizontal-scrolling-menu, the onselect function of the menu component returns an id number on selection, I want to pass that number inside the mapping function within the productlist.
Product list
import React from "react";
import Person from "./Person";MenuCat";
import MenuCat, {a, onSelect, selected} from "../components/
class ProductList extends React.Component {
state = {
error: null,
isLoaded: false,
items: []
};
componentDidMount() {
fetch("items.json")
.then(res => res.json())
.then(
result => {
this.setState({
isLoaded: true,
items: result
});
},
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return (
<div>
Error:{" "}
{error.message }
{console.log("check 1:", items)}
</div>
);
} else if (!isLoaded) {
return (
<div>
<img
src="loading.gif"
alt="loading"
height="100"
/>
</div>
);
} else {
return (
<div>
<MenuCat />
<div className="row">
{items.children[0].children.map(item => (
<Person
className="person"
Key={item.name}
Title={item.name}
imgSrc={item.image_url}
>
{item.base_price}
</Person>
))}
</div>
</div>
);
}
}
}
and the menuCat component looks like this
import React, { Component } from "react";
import ScrollMenu from "react-horizontal-scrolling-menu";
import "../menu.css";
// list of items
const list = [
{ name: "category1" , id : 0},
{ name: "category2" , id : 1},
{ name: "category3" , id : 2},
{ name: "category4" , id : 3},
{ name: "category5" , id : 4},
{ name: "category6" , id : 5},
{ name: "category7" , id : 6},
];
// One item component
// selected prop will be passed
const MenuItem = ({ text, selected }) => {
return <div className="menu-item">{text}</div>;
};
// All items component
// Important! add unique key
export const Menu = list =>
list.map(el => {
const { name } = el;
const { id } = el;
return <MenuItem text={name} key={id} />;
});
const Arrow = ({ text, className }) => {
return <div className={className}>{text}</div>;
};
const ArrowLeft = Arrow({ text: "<", className: "arrow-prev" });
const ArrowRight = Arrow({ text: ">", className: "arrow-next" });
export class Menucat extends Component {
state = {
selected: "0"
};
onSelect = key => {
console.log(`onSelect: ${key}`);
this.setState({ selected: key});
};
render() {
const { selected } = this.state;
// Create menu from items
const menu = Menu(list, selected);
return (
<div className="App">
<ScrollMenu
data={menu}
arrowLeft={ArrowLeft}
arrowRight={ArrowRight}
selected={selected}
onSelect={this.onSelect}
/>
</div>
);
}
}
export default Menucat;
I want the id generated from onselect function to be added instead of 0 in
{items.children[0].children.map(item => (
so that whenever the user clicks on a category item, the id of that category goes to the mapping function which will do the rest. I am aware that the category list is hardcoded, for now, I just want this communication between the components to happen, I want to pass the id from the menucat component to a something like a variable in product list that can go instead of the zero like {items.children[selected].children.map(item => (
you'll want to add an 'onSelect' prop to MenuCat to pass through the ScrollMenu's onSelect results, then a state value in ProductList to store the selected key. something like this:
ProductList
import React from "react";
import Person from "./Person";MenuCat";
import MenuCat, {a, onSelect, selected} from "../components/
class ProductList extends React.Component {
state = {
error: null,
isLoaded: false,
items: [],
selected: 0,
};
componentDidMount() {
fetch("items.json")
.then(res => res.json())
.then(
result => {
this.setState({
isLoaded: true,
items: result
});
},
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
constructor(props) {
super(props);
this.onSelect = this.onSelect.bind(this);
}
onSelect(key) {
this.setState({selected: key});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return (
<div>
Error:{" "}
{error.message }
{console.log("check 1:", items)}
</div>
);
} else if (!isLoaded) {
return (
<div>
<img
src="loading.gif"
alt="loading"
height="100"
/>
</div>
);
} else {
return (
<div>
<MenuCat onSelect={this.onSelect} />
<div className="row">
{items.children[this.state.selected].children.map(item => (
<Person
className="person"
Key={item.name}
Title={item.name}
imgSrc={item.image_url}
>
{item.base_price}
</Person>
))}
</div>
</div>
);
}
}
}
and MenuCat like
import React, { Component } from "react";
import ScrollMenu from "react-horizontal-scrolling-menu";
import "../menu.css";
// list of items
const list = [
{ name: "category1" , id : 0},
{ name: "category2" , id : 1},
{ name: "category3" , id : 2},
{ name: "category4" , id : 3},
{ name: "category5" , id : 4},
{ name: "category6" , id : 5},
{ name: "category7" , id : 6},
];
// One item component
// selected prop will be passed
const MenuItem = ({ text, selected }) => {
return <div className="menu-item">{text}</div>;
};
// All items component
// Important! add unique key
export const Menu = list =>
list.map(el => {
const { name } = el;
const { id } = el;
return <MenuItem text={name} key={id} />;
});
const Arrow = ({ text, className }) => {
return <div className={className}>{text}</div>;
};
const ArrowLeft = Arrow({ text: "<", className: "arrow-prev" });
const ArrowRight = Arrow({ text: ">", className: "arrow-next" });
export class Menucat extends Component {
state = {
selected: "0"
};
onSelect = key => {
console.log(`onSelect: ${key}`);
this.setState({ selected: key});
this.props.onSelect(key);
};
render() {
const { selected } = this.state;
// Create menu from items
const menu = Menu(list, selected);
return (
<div className="App">
<ScrollMenu
data={menu}
arrowLeft={ArrowLeft}
arrowRight={ArrowRight}
selected={selected}
onSelect={this.onSelect}
/>
</div>
);
}
}
export default Menucat;
you pass an 'onSelect' function to menucat, menucat calls it when the item is selected, and back in ProductList, its 'onSelect' function is then run, setting state which can then be used in your item selection.
make sense?
I am trying to make each individual list item clickable.
Here I have a color change state so that the color changes to red. But everytime I click one list item, it makes all of the boxes red. Again I want to select which ones to turn red, not turn all of them red. a hint in the right direction or a link would do fine.
import React, { Component } from 'react';
import './App.css';
import MainTool from './components/Layout/MainTool/MainTool.js';
import Aux from './hoc/Aux.js';
class App extends Component {
state = {
MainList: [
"GamePlay",
"Visuals",
"Audio",
"Story"
],
color: "white"
}
changeEle = () =>{
this.setState({color : "red"});
}
render() {
return (
<Aux>
<MainTool MainList = {this.state.MainList}
change = {this.changeEle}
color = {this.state.color}/>
</Aux>
);
}
}
export default App;
This MainTool just shoots my state arguments to Checkblock. Just for reference. Its unlikely the error is here although I have been wrong plenty times before.
import React from 'react';
import './MainTool.css';
import CheckBlock from '../../CheckBlock/CheckBlock';
const MainTool = props => {
return (
<div className = "mtborder">
<CheckBlock MainList = {props.MainList}
change = {props.change}
color = {props.color}/>
</div>
);
};
export default MainTool;
And here is my best guess at where the problem is. I used a loop to iterate through my state object array and print out the list and divs next to each list item. the divs being the elements I want to make clickable individually.
import React from 'react';
import './CheckBlock.css';
import Aux from '../../hoc/Aux';
const CheckBlock = props => {
console.log(props.change);
console.log(props.color);
let mainList = [];
for(let i = 0; i <= 3; i++)
{
mainList[i] = <li key = {i}
className = "nameBox">{props.MainList[i]}
<div onClick = {props.change}
style = {{backgroundColor: props.color}}
className = "clickBox"></div></li>
}
//console.log(dubi());
return (
<Aux>
<ul className = "mainList">{mainList}</ul>
<button>Enter</button>
</Aux>
);
};
export default CheckBlock;
You need a state based ListItem component with internal color state. No need to pass function as prop to change color. Use internal method
class ListItem extends Component {
state = { color : 'white' };
onClick = () => {
this.setState({ color: 'red' });
}
render () {
return (
<li key={i} className="nameBox">
{this.props.value}
<div onClick={this.onClick} style={{backgroundColor: props.color}}
className="clickBox">
</div>
</li>
);
}
}
const CheckBlock = props => {
console.log(props.change);
console.log(props.color);
let mainList = [];
for(let i = 0; i <= 3; i++)
{
mainList[i] = <ListItem key={i} value={props.MainList[i]} />
}
return (
<Aux>
<ul className = "mainList">{mainList}</ul>
<button>Enter</button>
</Aux>
);
};
I put jsfiddle together:
Let me know if there is a better practice to toggle element in React;
Cheers!
List item toggle jsfiddle
// ----------------APP-------------------
class App extends React.Component {
state = {
mainList: [
{
label: 'GamePlay',
id: 1,
},
{
label: 'Visuals',
id: 2,
},
{
label: 'Audio',
id: 3,
},
{
label: 'Story',
id: 4,
},
],
}
render() {
const { mainList } = this.state;
return (
<div>
<List mainList={mainList} />
</div>
);
}
}
// ----------------LIST-------------------
const List = ({ mainList }) => (
<div>
{mainList.map((listItem) => {
const { label, id } = listItem;
return (
<ListItem key={id} id={id} label={label} />
);
})}
</div>
);
// ----------------LIST-ITEM-------------------
class ListItem extends React.Component{
state = {
selected: false,
}
changeColor = () => {
const { selected } = this.state;
this.setState({selected: !selected})
}
render(){
const { label, id } = this.props;
const { selected } = this.state;
return console.log(selected ,' id - ', id ) || (
<button
className={selected ? 'green' : 'red'}
onClick= {() => this.changeColor()}
>
{label}
</button>
)
}
}