ReactJS onClick event on an array element - arrays

I need to select images in an image grid. Currently, I can only select one image at a time. When selecting one, the other unselects. I'd like to select every image I want (many images selected at a time). I can't activate a isToggle boolean on each element with onClick event.
class Gallery extends Component{
constructor(props) {
super(props);
this.state = {
//isToggleOn: true,
selected: '',
};
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleClick = key => {
this.setState(state => ({
//isToggleOn: !state.isToggleOn,
selected: key,
}));
//console.log(this.state)
}
render(){
//const classes = useStyles();
return (
<Container>
<Row >
<Col>
<div style={styles.root}>
<GridList cellHeight={160} style={styles.gridList} cols={3}>
{tileData.map((tile,i) => (
<GridListTile key={i} cols={tile.cols || 1} onClick={() => this.handleClick(tile)} >
<img src={tile.img} alt={tile.title} style={this.state.selected === tile ? styles.inputClicked:styles.inputNormal} />
</GridListTile>
))}
</GridList>
</div>
</Col>
</Row>
</Container>
);
}
}
export default Gallery;
I can only select one image at a time. I expect to select many at a time.

When the tile gets clicked, you need to add to an array of selected tiles like this:
handleClick = tile => {
this.setState({
selected: this.state.selected.concat([tile]),
});
}
then when rendering, you can check if the tile is selected something like this:
<img src={tile.img} alt={tile.title} style={isSelected(this.state.selected, tile) ? styles.inputClicked:styles.inputNormal} />
with:
isSelected = (selected, tile) => {
// some logic to check that the tile is already selected e.g.
return selected.find(tileItem => tileItem.title === tile.title)
}
Ensure to initialise your selected state to [] in constructor :
this.state = {
selected: [],
};
UPDATE:
If you want to remove tiles too, you'd have to do something like this:
handleClick = tile => {
const { selected } = this.state;
if(selected.find(item ==> item.title === tile.title)) {
// need to remove tile
this.setState({
selected: selected.filter(item => item.tile !== tile.title),
});
} else {
this.setState({
selected: this.state.selected.concat([tile]),
});
}
}

Related

React.js: state is not updating in parent component

I have search filter and categories. I just want to have a possibility to reset state in single page application.
Due to React.js I guess I do everything correct to pass state from parent to child and then from child to parent. But, unfortunately, something is going wrong. I tried a lot and what I discovered, that onAddCategory() in DropdownGroup doesn't update current state.
Sorry in advance, I add whole code, my be something there could affect this. But i guess you can see first halfs of two codes and it will be enough.
Thank you in advance.
I have parent component:
class DropdownGroup extends React.Component {
constructor(props) {
super(props);
this.state = {
categories: [], // we have empty array, that pass to CategoryDropdown
};
this.onAddCategory = this.onAddCategory.bind(this);
}
onAddCategory(newCategory) {
this.setState(() => ({
categories: newCategory,
}));
}
onSelectCategory(path) {
this.props.onChangeEvents(path);
}
render() {
const months = ['January', 'February' ... ];
const eventsType = ['Party', 'Karaoke ... ];
const { categories } = this.state;
return (
<ButtonToolbar className="justify-content-center pb-4 pt-4">
{ console.log(categories) }
<CategoryDropdown
items={eventsType}
homePath="events"
path="events/categories/"
categories={categories} // here we pass our empty array (or updated later)
addCategories={this.onAddCategory} // this is what helps to update our array
onApply={(path) => this.onSelectCategory(path)}
/>
<MyDropdown
id="sort-by-month"
name="By month"
items={months}
onSelect={(e) => this.onSelectCategory(`events/month/${e}`)}
/>
<DropdownWithDate
oneDate="events/date/"
rangeDate="events/dates?from="
onApply={(path) => this.onSelectCategory(path)}
/>
<Button
onClick={() => this.setState({ categories: [] })} // here we can reset the value of our array
className="m-button ml-5"
>
Reset
</Button>
</ButtonToolbar>
);
}
}
DropdownGroup.propTypes = {
onChangeEvents: PropTypes.any.isRequired,
};
export default DropdownGroup;
and this is child component
class CategoryDropdown extends Component {
constructor(props) {
super(props);
this.state = {
visible: false,
selected: this.props.categories, // here we get values from props (now empty, then updated values)
};
this.onVisibleChange = this.onVisibleChange.bind(this);
}
onVisibleChange(visible) {
this.setState({
visible: visible,
});
}
saveSelected(selectedKeys) {
this.setState({
selected: selectedKeys,
});
}
addCategories() {
this.props.addCategories(this.state.selected); // here props are updated
}
confirm() {
const { selected } = this.state;
this.addCategories(this.state.selected);
const { homePath, path } = this.props;
if (selected.length > 0) {
this.props.onApply(path + selected);
} else {
this.props.onApply(homePath);
}
this.onVisibleChange(false);
}
render() {
const { visible } = this.state;
const { items } = this.props;
const menu = (
<Menu
multiple
onSelect={(e) => { this.saveSelected(e.selectedKeys); }}
onDeselect={(e) => { this.saveSelected(e.selectedKeys); }}
>
{items.map((item) => (
<MenuItem
key={item.replace('\u0020', '\u005f').toLowerCase()}
>
{item}
</MenuItem>
))}
<Divider />
<MenuItem disabled>
<Container
className="text-center "
style={{
cursor: 'pointer',
pointerEvents: 'visible',
}}
onClick={() => {
this.confirm();
}}
>
Select
</Container>
</MenuItem>
</Menu>
);
return (
<Dropdown
trigger={['click']}
onVisibleChange={this.onVisibleChange}
visible={visible}
closeOnSelect={false}
overlay={menu}
>
<Button className="m-button">By Category</Button>
</Dropdown>
);
}
}
CategoryDropdown.propTypes = {
onApply: PropTypes.any.isRequired,
items: PropTypes.any.isRequired,
path: PropTypes.string.isRequired,
homePath: PropTypes.string.isRequired,
categories: PropTypes.array.isRequired,
addCategories: PropTypes.any.isRequired,
};
export default CategoryDropdown;

Want to show the data in a dropdown every item as an option

class DropDown extends Component {
constructor(){
super()
this.state = {
item: [],
isLoaded: true,
}
}
// here I have fetch the data from api
componentDidMount() {
fetch('link')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoaded: false,
item: responseJson.drawingInfo.renderer.uniqueValueInfos,
})
})
}
render() {
const {item} = this.state;
// here I have map the array of data. And now wanna show it in a dropdown where every item is an option an we can select them
const itemDropdown = item.map((division, index)=> (
<div key={index}>
<option>{division.value}</option>
</div>
))
return (
{/*here I tried to show the data as dropdown option...but I got one option where all the data resides*/}
<div>
<ReactBootStrap.DropdownButton variant = 'transparent' id = "dropdown-button" title="Dropdown button" >
< ReactBootStrap.Dropdown.Item > {itemDropdown} </ReactBootStrap.Dropdown.Item>
</ReactBootStrap.DropdownButton>
</div>
);
}
}
react bootstrap dropdown makes working with react & bootstrap a bit easier:
render (){
const {item} = this.state;
return (
<DropdownButton title="Dropdown">
{ item.map((division, index)=> (
<MenuItem>{division}</MenuItem>
)
</DropdownButton>
);
}

React show/hide content

I'm trying to make a toggle content button with React. But I can only get it to open, not to close when I click on it again. Can someone please take a look and let me know what I need to change within the code to accomplish it?
Here's what I have so far:
class Test extends React.Component {
constructor(props) {
super(props)
this.state = {
activeLocation: 0,
}
}
changeActiveLocation = (activeLocation) => {
this.setState({
activeLocation: activeLocation,
});
}
render() {
const activeLocation = company.locations[this.state.activeLocation];
return (
{company.locations.map((location, index) => (
<div className="test-item">
<div className="test-item-container" onClick={() => {this.changeActiveLocation(index)}}>
<div className="test-item-header">
<h3>Text goes here!</h3>
<a><FontAwesomeIcon icon={(this.state.activeLocation === index) ? 'times' : 'chevron-right'} /></a>
</div>
</div>
</div>
))}
)
}
}
Thank you!
You're setting the active location to be the same location that you've clicked already so the this.state.activeLocation === index is always true. I would refactor the locations to their own component with an isOpen state value that gets updated when the location is clicked. So like the following:
// test class
class Test extends React.Component {
constructor(props) {
super(props)
this.state = {
activeLocation: 0,
}
}
changeActiveLocation = (activeLocation) => {
this.setState({
activeLocation: activeLocation,
});
}
render() {
const activeLocation = company.locations[this.state.activeLocation];
return (
{company.locations.map((location, index) => (
<LocationItem location={location} onClick={() => this.changeActiveLocation(index)} />
))}
)
}
}
// LocationItem
class LocationItem extends React.Component {
state = { isOpen: false };
handleClick = () => {
this.setState(prevState => { isOpen: !prevState.isOpen});
// call parent click to set new active location if that's still needed
if(this.props.onClick) this.props.onClick;
}
render() {
return <div className="test-item">
<div className="test-item-container" onClick={this.handleClick}>
<div className="test-item-header">
<h3>Text goes here!</h3>
<a><FontAwesomeIcon icon={(this.state.isOpen ? 'times' : 'chevron-right'} /></a>
</div>
</div>
</div>
}
}

I want to add value to an array on click in react

I want to add the value to an array in state onClick event in React.
So far with the onSelectRooms function, I can get the value with e.target.id but It doesn't append the value to the array selectedRooms that's on state.
onSelectRooms = (e) => {
const newItem = e.target.id;
this.setState({
selectedRooms: [...this.state.selectedRooms, newItem]});
}
export default class ExportReportRoomSelectionModal extends React.Component {
constructor(props) {
super(props);
const roomOrder = configContext.value.roomOrder;
this.state = {
rooms: roomOrder,
selectedRooms: [],
};
this.onSelectRooms = this.onSelectRooms.bind(this);
}
onSelectRooms = (e) => {
const newItem = e.target.id;
this.setState({
selectedRooms: [...this.state.selectedRooms, newItem]});
}
render() {
return (
<Modal>
<Modal.Header>
<Modal.Title>Title</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Number of rooms: {this.state.rooms.length}</p>
<p>Rooms:</p>
<Grid fluid={true}>
<Row className="show-grid">
{ this.state.rooms.map((name, i ) =>
<Col key={i}>
<Panel onClick={this.onSelectRooms}>
<Panel.Heading id={name}>
{name}
</Panel.Heading>
</Panel>
</Col>
)}
</Row>
</Grid>
</Modal.Body>
</Modal>);
}
}
Create a Input field and define a name for this input field.
And collect data from this input field by this.refs.inputFieldName.value
and push this inside your declared array variable.
Below Git Project link with full crud and Documentation.
Try it
https://gitlab.com/ripon52/reactcrud
You can pass index of clicked room to onSelectRooms function.
export default class ExportReportRoomSelectionModal extends React.Component {
constructor(props) {
super(props);
const roomOrder = configContext.value.roomOrder;
this.state = {
rooms: roomOrder,
selectedRooms: [],
};
}
onSelectRooms = (e, index) => {
this.setState(prevState => ({
selectedRooms: [...prevState.selectedRooms, index]
}));
}
render() {
return (
<Modal>
<Modal.Header>
<Modal.Title>Title</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Number of rooms: {this.state.rooms.length}</p>
<p>Rooms:</p>
<Grid fluid={true}>
<Row className="show-grid">
{ this.state.rooms.map((name, i ) =>
<Col key={i}>
<Panel onClick={() => this.onSelectRooms(i)}>
<Panel.Heading id={name}>
{name}
</Panel.Heading>
</Panel>
</Col>
)}
</Row>
</Grid>
</Modal.Body>
</Modal>);
}
}
You can try this,
const joined = this.state.selectedRooms.concat(newItem);
this.setState({ selectedRooms: joined })
change onSelectRooms() with below code and check
onSelectRooms = (e) => {
const newItem = e.target.id;
let roomArray = this.state.selectedRooms;
roomArray.push(newItem); //add value in local array
this.setState({selectedRooms: roomArray}); //replace selectedRooms with local arry
}
enjoy !

How to use react-virtualized with dynamic list height

I am trying to implement react-virtualized into my project. I have a side panel with a list of subdivisions. I would like to have an accordion-like functionality when the user selects an item. When the page first loads it looks like it is working correctly.
However when I start to scroll down the list looks like this
and here is code
const mapStateToProps = state => ({
windowHeight: state.dimensions.windowHeight,
sbds: new Immutable.List(state.sbds.data),
sbd: state.sbd.data
})
#connect(mapStateToProps)
export default class SBD extends Component {
static propTypes = {
windowHeight: PropTypes.number,
sbds: PropTypes.instanceOf(Immutable.List),
sbd: PropTypes.object
}
constructor(props) {
super(props)
this.state = {
listHeight: props.windowHeight - 250,
listRowHeight: 60,
overscanRowCount: 10,
rowCount: props.sbds.size,
scrollToIndex: undefined,
collapse: true
}
}
componentWillUnmount() {
}
shouldComponentUpdate(nextProps, nextState) {
const {sbds} = this.props
if (shallowCompare(this, nextProps, nextState))
return true
else return stringify(sbds) !== stringify(nextProps.sbds)
}
_handleSelectRow = selected => {
sbdRequest(selected)
const obj = {[selected.id]: true}
this.setState(obj)
}
render() {
const {
listHeight,
listRowHeight,
overscanRowCount,
rowCount,
scrollToIndex
} = this.state
return (
<div>
<SearchGroup />
<Card className='border-0 mt-10 mb-0'>
<CardBlock className='p-0'>
<AutoSizer disableHeight>
{({width}) => (
<List
ref='List'
className=''
height={listHeight}
overscanRowCount={overscanRowCount}
rowCount={rowCount}
rowHeight={listRowHeight}
rowRenderer={this._rowRenderer}
scrollToIndex={scrollToIndex}
width={width}
/>
)}
</AutoSizer>
</CardBlock>
</Card>
</div>
)
}
_getDatum = index => {
const {sbds} = this.props
return sbds.get(index % sbds.size)
}
_rowRenderer = ({index}) => {
const {sbd} = this.props
const datum = this._getDatum(index)
return (
<span key={datum.id}>
<Button
type='button'
color='link'
block
onClick={() => this._handleSelectRow(datum)}>
{datum.name}
</Button>
<Collapse isOpen={this.state[datum.id]}>
<Card>
<CardBlock>
FOO BAR
</CardBlock>
</Card>
</Collapse>
</span>
)
}
}
You're not setting the style parameter (passed to your rowRenderer). This is the thing that absolutely positions rows. Without it, they'll all stack up in the top/left as you scroll.
https://bvaughn.github.io/forward-js-2017/#/32/1

Resources