How to collect Switch value in React JS + Ant Design - reactjs

I'm sorry for my basic knowledge and my basic english :)
My Question is: How to concenate switch value [I use Switch for each record in table]
This is the table
https://ibb.co/3TVLBK6
I've created table with one cell/field using Switch (On/Off)
And i want get the switch value when they are on
And here is the code
const columnsTableDepartmentModal = [
{
title: 'No',
dataIndex: 'no',
key: 'no',
},
{
title: 'Department',
dataIndex: 'department',
key: 'department',
},
{
title: 'Select',
dataIndex: 'select_department',
key: 'select_department',
render: (e, record) => (
<Switch
defaultChecked={e}
onChange={
(value) => onChangeSwitch(value,record)
}
checkedChildren="Yes"
unCheckedChildren="No"
/>
),
}];
This is what i now try
function onChangeSwitch(isSelect,record){
console.log(e); // True / False
console.log(record); // True / False
if(isSelect){
// push data to array
}
if(!isSelect){
// pop data from array
}
}
This is how i show the table
<Modal
title={modalDepartmentTitle}
visible={visibleDepartment}
width={800}
onOk={handleOkDepartment}
onCancel={handleCancelDepartment}
footer={[
<Button key="submit" type="primary" onClick={handleOkDepartment}>OK</Button>,
<Button key="button" type="danger" onClick={handleDeleteDepartment}>DELETE</Button>,
<Button key="back" onClick={handleCancelDepartment}>CANCEL</Button>,
]}
>
<Table
columns={columnsTableDepartmentModal}
dataSource={stateDepartment.data}
pagination={false}
scroll={{y: 325}}
/>
</Modal>
Expected result: 1,3,4

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import Switch from 'react-switch';
class App extends Component {
constructor() {
super();
this.state = {
checkedPos: [],
info: [],
};
}
componentWillMount()
{
let tmp = []
let pos = []
for (var i = 1; i < 6; i++) {
tmp.push("Info " + i)
pos.push(false);
}
this.setState({
info: tmp,
checkedPos: pos
})
}
handleChange(index, info)
{
if (!this.state.checkedPos[index])
{
this.setState(prev => ({
checkedPos: prev.checkedPos.map((val, i) => !val && i === index ? true : val),
}))
}
else if (this.state.checkedPos[index])
{
this.setState( prev => ({
checkedPos: prev.checkedPos.map((val, i) => val && i === index ? false : val),
}))
}
}
render() {
const listItems = this.state.info.map((item, index) =>
<div>
{item}
<Switch checked={this.state.checkedPos[index]}
onChange={ () => this.handleChange(index, this.state.info[index])}/>
{" Value is " + this.state.checkedPos[index]}
</div>
);
return (
<div>
{listItems}
</div>
);
}
}
render(<App />, document.getElementById('root'));
Demo here

Acording to #jose answer i've implemented to hook concept with this code
const [theArray, setTheArray] = useState([]);
const addEntry = useCallback((value) => {
setTheArray([...theArray, `${value}`]);
});
Then in function we can add value
function onChangeSwitch(isSelect,record){
console.log(isSelect); // True / False
console.log(record);
addEntry(record.no);
if(isSelect){
// push data to array
}
if(!isSelect){
// pop data from array
}
}
So when we display {enty}
<div key="adkfkdfkda">{theArray.map(entry =>
<span key={entry}>{entry},</span>
)}
</div>
We got value merged in string format
https://ibb.co/nQFK1C4
Thanks.

Related

React Multi Carousel - Problem with customButtonGroup

I've been struggling with what seems like a simple solution for far too long. I'm new to typescript and new to react.
I'm trying to use the react-mulit-carousel NPM package.
I'm able to get the customButtonGroup to work successfully in the sandbox:
https://codesandbox.io/s/fervent-rain-332mn?file=/src/App.js:834-913
But when I try to implement that in my SPFX solution i get the following error:
Type '{}' is missing the following properties from type '{ [x: string]: any; next: any; previous: any; goToSlide: any; }': next, previous, goToSlide
import * as React from 'react';
import { IBrandsCarouselProps } from './IBrandsCarouselProps';
import { IBrandsCarouselState } from './IBrandsCarouselState';
import { IBrand } from './IBrand';
import styles from '../../../styles/styles.module.scss';
import { SPHttpClient } from '#microsoft/sp-http';
import Carousel from 'react-multi-carousel';
import 'react-multi-carousel/lib/styles.css';
import '../../../styles/react-carousel.scss';
import { getNextElement } from 'office-ui-fabric-react';
const responsive = {
desktop: {
breakpoint: { max: 4000, min: 768 },
items: 4,
partialVisibilityGutter: 0
},
tablet: {
breakpoint: { max: 768, min: 480 },
items: 3,
partialVisibilityGutter: 30
},
mobile: {
breakpoint: { max: 480, min: 0 },
items: 2,
partialVisibilityGutter: 30
}
};
export default class BrandsCarousel extends React.Component<IBrandsCarouselProps, IBrandsCarouselState>{
constructor(props) {
super(props);
this.state = {
displayedBrands: [],
isLoading: true
};
}
/**
* Loads data from a list by using a cached view
*/
public loadBrandsFromList(): Promise<IBrand[]> {
const queryUrlGetAllItems: string = `[[HIDDEN]]`;
return this.props.context.spHttpClient.get(
queryUrlGetAllItems,
SPHttpClient.configurations.v1)
.then(
(response: any) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
return Promise.resolve(new Error(JSON.stringify(response)));
}
})
.then((data: any) => {
let documents: IBrand[] = [];
if (data) {
for (let i = 0; i < data.value.length; i++) {
let item = data.value[i];
var doc: IBrand = {
Title: item.Title,
Image: item.Image.Url ? item.Image.Url : "No Image Set",
Url: item.Url.Url,
Business: item.Business
};
documents.push(doc);
}
}
return documents;
}).catch((ex) => {
// console.log("readDocumentsFromLibrary > spHttpClient.get()...catch:", ex);
throw ex;
});
}
public render(): React.ReactElement<IBrandsCarouselProps> {
// Sorting is Done in the Rest Call
let items = this.state.displayedBrands;
// create a new list that filters by the tags
// Business is an array of strings
// If the item has an array value that matches the Props Business
if (this.props.Business != "All") {
let filteredItems = [];
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.Business.indexOf(this.props.Business) > -1) {
filteredItems.push(item);
}
}
items = filteredItems;
}
const ButtonGroup = ({ next, previous, goToSlide, ...rest }) => {
const {
carouselState: { currentSlide }
} = rest;
return (
<div className="carousel-button-group">
<div
className={currentSlide === 0 ? "disable" : ""}
onClick={() => previous()}
>
Prev
</div>
<div onClick={() => next()}>Next</div>
<div onClick={() => goToSlide(currentSlide + 1)}> Go to any slide </div>
</div>
);
};
return (
<div className={styles["brands-slider"] + " " + styles["card-docs-slider"] + " hub-carousel"}>
{this.props.IsTitle && this.props.Title != "" &&
<div className={styles["widget-header"]}>
<span className={styles["view"]}>{this.props.Title}</span>
</div>
}
<div className={styles["card-slider"]}>
{items && items.length > 0 &&
<Carousel
responsive={responsive}
arrows
additionalTransfrom={0}
itemClass={"react-carousel-item"}
minimumTouchDrag={80}
partialVisible
renderButtonGroupOutside
customButtonGroup={<ButtonGroup />}
>
{items.map((item) => {
return (
<a href={item.Url} className={styles["block-link"]} target="_blank">
<img src={item.Image} alt={item.Title} />
</a>
);
})
}
</Carousel>
}
{items && items.length == 0 &&
<p>No Brands found. Please, check the List</p>
}
</div>
</div>
);
}
public componentDidMount() {
this.loadBrandsFromList().then(
//resolve
(documents: IBrand[]) => {
this.setState({
displayedBrands: documents,
isLoading: false,
});
},
//reject
(data: any) => {
this.setState({
displayedBrands: [],
isLoading: false,
isErrorOccured: true,
errorMessage: data
});
}
).catch((ex) => {
this.setState({
displayedBrands: [],
isLoading: false,
isErrorOccured: true,
errorMessage: ex.errorMessage
});
});
}
}
Any help would be greatly appreciated. Thank you!
I was able to figure it out. I needed to pass parameters. Oops!
Hopefully this can help out another JSX, Typescript, React beginner in the future.
<Carousel
responsive={responsive}
arrows
additionalTransfrom={0}
itemClass={"react-carousel-item"}
minimumTouchDrag={80}
partialVisible
renderButtonGroupOutside
customButtonGroup={<ButtonGroup
next={this.props.next}
previous={this.props.previous}
rest={this.props.rest}
/>}
>
Here's the Custom Button group if it helps as well. I couldn't find the documentation to hide the next button.
const ButtonGroup = ({ next, previous, ...rest }) => {
const {
carouselState: { currentSlide, totalItems, slidesToShow }
} = rest;
return (
<div className="carousel-button-group">
<button aria-label="Go to previous slide"
className={currentSlide === 0 ? "disable" : "react-multiple-carousel__arrow react-multiple-carousel__arrow--left"}
onClick={() => previous()}></button>
<button aria-label="Go to next slide"
className={currentSlide === totalItems - slidesToShow ? "disable" : "react-multiple-carousel__arrow react-multiple-carousel__arrow--right"}
onClick={() => next()}></button>
</div>
);
};

How to add right click menu to react table row, and access its properties?

I've added react-table package to my project and everything is fine, but I also wanted to have a possibility to right click on a row and perform some actions on it (cancel, pause etc). I'm using React with Typescript but I hope it doesn't add any complexity.
My initial idea was to use react-contextify, however I can't find any working examples that would combine react-table and react-contextify together.
The only "working" example I have found is this one:
React Context Menu on react table using react-contexify
I ended up not using react-contextify and it "kind of works" but I'm not totally certain about this one as I sometimes keep getting exceptions like this:
Uncaught TypeError: Cannot read property 'original' of undefined
The code I have now is this:
const columns = [
{
Header: "Name",
accessor: "name"
},
{
Header: "Age",
accessor: "age",
Cell: (props: { value: React.ReactNode }) => (
<span className="number">{props.value}</span>
)
},
{
id: "friendName", // Required because our accessor is not a string
Header: "Friend Name",
accessor: (d: { friend: { name: any } }) => d.friend.name // Custom value accessors!
},
{
Header: (props: any) => <span>Friend Age</span>, // Custom header components!
accessor: "friend.age"
}
];
return (
<div>
<ContextMenuTrigger id="menu_id">
<ReactTable
data={data}
columns={columns}
showPagination={false}
getTdProps={(
state: any,
rowInfo: any,
column: any,
instance: any
) => {
return {
onClick: (e: any, handleOriginal: any) => {
const activeItem = rowInfo.original;
console.log(activeItem);
},
onContextMenu: () => {
console.log("contextMenu", rowInfo);
this.setState({
showContextMenu: true,
rowClickedData: rowInfo.original
});
}
};
}}
/>
</ContextMenuTrigger>
{this.state.showContextMenu ? (
<MyAwesomeMenu clickedData={this.state.rowClickedData} />
) : null}
</div>
);
}
}
const MyAwesomeMenu = (props: { clickedData: any }) => (
<ContextMenu id="menu_id">
<MenuItem
data={props.clickedData}
onClick={(e, props) => onClick({ e, props })}
>
<div className="green">ContextMenu Item 1 - {props.clickedData.id}</div>
</MenuItem>
</ContextMenu>
);
const onClick = (props: {
e:
| React.TouchEvent<HTMLDivElement>
| React.MouseEvent<HTMLDivElement, MouseEvent>;
props: Object;
}) => console.log("-------------->", props);
What is the best (and simplest) way to add a context menu to react-table so I can use clicked row's props? I really like react-contextify but haven't found any examples.
Thanks
React Hooks exmaple on dev.to
Class Based Compnent example on codepen
class App extends React.Component {
constructor() {
super();
this.state = {
value: ''
};
}
render() {
return(
<div>
{
['row1', 'row2', 'row3'].map((row) => {
return (
<ContextMenu
key={row}
buttons={[
{ label: 'Editovat', onClick: (e) => alert(`Editace ${row}`) },
{ label: 'Smazat', onClick: (e) => alert(`Mažu ${row}`) }
]}
>
<div className="row">{row}</div>
</ContextMenu>
);
})
}
</div>
);
}
}
class ContextMenu extends React.Component {
static defaultProps = {
buttons: []
};
constructor() {
super();
this.state = {
open: false
};
}
componentDidMount() {
document.addEventListener('click', this.handleClickOutside);
document.addEventListener('contextmenu', this.handleRightClickOutside);
}
handleClickOutside = (e) => {
if (!this.state.open) {
return;
}
const root = ReactDOM.findDOMNode(this.div);
const context = ReactDOM.findDOMNode(this.context);
const isInRow = (!root.contains(e.target) || root.contains(e.target));
const isInContext = !context.contains(e.target);
if (isInRow && isInContext) {
this.setState({
open: false
});
}
}
handleRightClickOutside = (e) => {
if (!this.state.open) {
return;
}
const root = ReactDOM.findDOMNode(this.div);
const isInRow = !root.contains(e.target);
if (isInRow) {
this.setState({
open: false
});
}
}
handleRightClick = (e) => {
e.preventDefault();
console.log(e.nativeEvent, window.scrollY);
this.setState({
open: true,
top: window.scrollY + e.nativeEvent.clientY,
left: e.nativeEvent.clientX,
});
}
render() {
return (
<div
onContextMenu={this.handleRightClick}
ref={(node) => this.div = node}
>
{this.props.children}
{
!this.state.open
? null
: <div
className="context"
ref={(div) => this.context = div}
style={{ top: this.state.top, left: this.state.left }}
>
<ul>
{
// button - name, onClick, label
this.props.buttons.length > 0 &&
this.props.buttons.map((button) => {
return <li key={button.label}>
<a href="#" onClick={button.onClick}>
{button.label}
</a>
</li>
})
}
</ul>
</div>
}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));

How to render Array data in Row of react-table

I'm new in React. Using react-table component to render data from firebase and that is working well.
constructor(props) {
super(props);
this.state = {
vehicles: []
};
}
getvehicles() {
let vehicles = [];
firebase
.database()
.ref(`vehicles`)
.once('value', snapshot => {
snapshot.forEach(level1 => {
level1.forEach(level2 => {
const vehicle = level2.val();
vehicle.pictures && vehicles.push(vehicle);
});
});
this.setState({
vehicles
});
});
}
From here Data comming in react-table
return (
<div style={style}>
<div>
<ReactTable
style={{ marginLeft: '-80%', marginRight: '-80%' }}
data={this.state.vehicles}
filterable
defaultFilterMethod={(filter, row) =>
String(row[filter.id]) === filter.value
}
columns={vehiclesColumns}
SubComponent={row => {
return ;
}}
/>
</div>
</div>
);
Problem is, that I'm getting "pictures" from database, and want to put them in "subcomponent" and I do not know how? Anyone to help?
SubComponent={row => {
return (
<div>
some code here
</div>
);
Image 1 Example of data loaded from firebase
Image 2 Example of table "click on arrow and show pics from database"
=====================
New question
Ok on the end I manage to make all together but still getting error 'imageUrls' is not defined.
For me this is nightmare to find where is problem, so is there anyone who can re-check this code totally and just make comment how to fix and where is problem?!
import React, { Component } from 'react';
import ReactTable from 'react-table';
import 'react-table/react-table.css';
import firebase from 'firebase';
import Moment from 'moment';
import { storage } from 'firebase';
import _ from 'underscore';
export const getFileByPath = async query =>
await storage
.ref()
.child(query)
.getDownloadURL();
class App extends Component {
constructor(props) {
super(props);
this.state = {
vehicles: []
};
this.state = {
imageUrls: []
};
}
prepareImages = () => {
Promise.all(
_.map(this.props.images, image => {
return storage.getFileByPath(image.remoteUri);
})
).then(results =>
_.each(results, result => {
const imageUrls = this.state.imageUrls;
imageUrls.push(result);
this.setState({ imageUrls: imageUrls, loading: false });
})
);
};
componentWillMount() {
this.getvehicles();
}
getvehicles() {
let vehicles = [];
firebase
.database()
.ref(`vehicles`)
.once('value', snapshot => {
snapshot.forEach(level1 => {
level1.forEach(level2 => {
const vehicle = level2.val();
vehicle.pictures && vehicles.push(vehicle);
});
});
this.setState({
vehicles
});
});
}
render() {
const vehiclesColumns = [
{
columns: [
{
Header: 'Vehicle ID',
id: 'vehicleID',
accessor: d => d.vehicleID,
filterMethod: (filter, row) =>
row[filter.id].startsWith(filter.value)
},
{
Header: 'Terminal',
id: 'terminal',
accessor: d => d.terminal,
filterMethod: (filter, row) =>
row[filter.id].startsWith(filter.value)
},
{
Header: 'Time',
id: 'timestamp',
accessor: d => {
return Moment(d.timestamp)
.local()
.format('DD-MMMM-YYYY', 'at', true);
},
filterMethod: (filter, row) =>
row[filter.id].startsWith(filter.value)
},
{
Header: 'User',
id: 'user',
accessor: d => d.user,
filterMethod: (filter, row) =>
row[filter.id].startsWith(filter.value)
}
]
}
];
return (
<div style={style}>
<div>
<ReactTable
style={{ marginLeft: '-80%', marginRight: '-80%' }}
data={this.state.vehicles}
filterable
defaultFilterMethod={(filter, row) =>
String(row[filter.id]) === filter.value
}
columns={vehiclesColumns}
SubComponent={row => {
return (
<div>
{_.map(imageUrls, image => (
<img src={image} key={image} />
))}
</div>
);
}}
/>
</div>
</div>
);
}
}
const style = {
display: 'flex',
justifyContent: 'center'
};
export default App;
I think what you are trying to do is something like:
// Somewhere else, maybe a different doc
const SubComponent = () => {
<div>Content here</div>
}
// [...previous Code]
return (
<ReactTable
style={{ marginLeft: "-80%", marginRight: "-80%" }}
data={this.state.vehicles}
filterable
defaultFilterMethod={(filter, row) =>
String(row[filter.id]) === filter.value
}
columns={vehiclesColumns}
>
<SubComponent props={somePropsHere} />
</ReactTable>
)
Am I right? The children of a Component should not be given as a property.
Regards

Deleting component elements from an array in reactjs

I'm fairly new to react. What I'm trying to do is to delete a component from an array given an index when the "[x]" button is clicked.
From what I understood react re-renders the Component whenever the state has changed.
The labels variable on the render() method is an array of components and also has other child components. When the user clicks the [x] on one of the components, it would pass the index of that to the class function closeLabelHandler() and assign the state objects, indexToDelete and isDeletingLabel to the index of the element and true, respectively.
Since I am changing a state object, I was thinking that this during the re-render an element would be deleted from the labels array but alas, it doesn't.
Here's my code:
import React, { Component } from 'react';
import "./ImageContainer.css";
import { Stage, Layer, Image, Tag, Text, Label } from 'react-konva';
import ToolsContainer from '../ToolsContainer/ToolsContainer';
class ImageContainer extends Component {
state = {
showImageContainer: true,
canvasHeight: 0,
canvasWidth: 0,
canvasImageUrl: "",
image: null,
commentsArray: [],
labelCount: 0,
isDeletingLabel: false,
indexToDelete: -1
}
componentDidMount() {
let stage = this.refs.stage
const imgObj = new window.Image();
imgObj.src = this.props.selectedImageURI
imgObj.onload = () => {
this.setState({ image: imgObj })
this.setState({ canvasWidth: imgObj.width, canvasHeight: imgObj.height });
let canvasImageUrl = stage.toDataURL();
this.setState({ canvasImageUrl: canvasImageUrl })
}
}
getLabelCount = (count) => {
this.setState({ labelCount: count })
}
displayContainerHandler = () => {
this.props.showImageContainer(!this.state.showImageContainer)
}
downloadImageHandler = () => {
let a = document.createElement('a');
a.href = this.state.canvasImageUrl.replace("image/png", "image/octet-stream");
a.download = 'shot.png';
a.click();
}
closeLabelHandler = (index) => {
this.setState({
isDeletingLabel: true,
indexToDelete: index
})
console.log("[closeLabelHandler] " + index)
}
render() {
console.log("[ImageContainer][render]" + this.state.commentsArray)
let labels = [];
for (let i = 0; i < this.state.labelCount; i++) {
labels.push(
<Label key={i} draggable={true} x={150 + i * 2} y={150 + i * 2} >
<Tag
fill="black"
pointerWidth={10}
pointerHeight={10}
lineJoin='round'
shadowColor='black'
/>
<Text
text="Insert Comment Here"
fontFamily='Calibri'
fontSize={18}
padding={5}
fill='white'
/>
<Text
text="[x]"
fontFamily='Calibri'
fontSize={18}
x={170}
fill='black'
onClick={() => this.closeLabelHandler(i)}
/>
</Label>
)
if (this.state.isDeletingLabel) {
labels.splice(this.state.indexToDelete, 1)
this.setState({
isDeletingLabel: false,
indexToDelete: -1
})
}
}
return (
<div className="ImageContainer" >
<button className="ImageContainer-close-button " onClick={this.displayContainerHandler}>[x]</button>
<Stage ref="stage" height={this.state.canvasHeight * .5} width={this.state.canvasWidth * .5} >
<Layer>
<Image image={this.state.image} scaleX={0.5} scaleY={0.5} />
{labels}
</Layer>
</Stage>
<ToolsContainer getLabelCount={count => this.getLabelCount(count)} />
<button className="pure-button" onClick={() => this.downloadImageHandler()}>Download</button>
</div>
)
}
}
Any help would be appreciated.
This is a simple way to achive what you want. You should not change your state directly, it could cause inconsistency to your application.
import React, { Component } from "react";
class Books extends Component {
state = {
books: [{ id: 1, title: "Book 1" }, { id: 2, title: "Book 2" }]
};
handleDelete = book => {
const books = this.state.books.filter(b => b.id !== book.id);
this.setState({ books });
};
render() {
return (
<ul>
{this.state.books.map(book => (
<li key={book.id}>
{book.title}{" "}
<button onClick={() => this.handleDelete(book)}>x</button>
</li>
))}
</ul>
);
}
}
export default Books;

How do you select a single cell with react-data-grids and use the data in that cell elsewhere

I have a populated grid by using react-data-grids by addazle and I'm trying to select a cell and have a modal pop up with the data from that cell. I have enableCellSelect={true} and I know I needd to use a React.createClass but I'm not sure where to go from there. Thanks in advance!
let onClick = React.createClass({
render(){
return(
<div onClick={this.showModal}>
</div>
)
}
})
export class Modal extends Component{
constructor(props){
super(props)
this.state={}
}
render(){
return(
<div>
<ReactDataGrid
enableCellSelect={true}
columns={columns}
rowGetter={this.getRows}
rowsCount={this.state.rows.length}
getSubRowDetails={this.getSubRowDetails}
onCellExpand={this.onCellExpand}
minHeight={500}
/>
</div>
)
}
}
Did you read the examples from react-data-grid webpage? You may find your solution here: http://adazzle.github.io/react-data-grid/examples.html#/cell-selection-events
You create a function onCellSelected:
onCellSelected = ({ rowIdx, idx }) => {
this.grid.openCellEditor(rowIdx, idx);
};
When you call your component
<ReactDataGrid
ref={ node => this.grid = node }
rowKey="id"
columns={this._columns}
rowGetter={this.rowGetter}
rowsCount={this._rows.length}
enableRowSelect="multi"
minHeight={500}
onRowSelect={this.onRowSelect}
enableCellSelect={true}
onCellSelected={this.onCellSelected}
onCellDeSelected={this.onCellDeSelected} />
Hereunder, the complete example of the link:
const ReactDataGrid = require('react-data-grid');
const exampleWrapper = require('../components/exampleWrapper');
const React = require('react');
class Example extends React.Component {
constructor(props) {
super(props);
this._columns = [
{ key: 'id', name: 'ID' },
{ key: 'title', name: 'Title', editable: true },
{ key: 'count', name: 'Count' }
];
let rows = [];
for (let i = 1; i < 1000; i++) {
rows.push({
id: i,
title: 'Title ' + i,
count: i * 1000,
active: i % 2
});
}
this._rows = rows;
this.state = { selectedRows: [] };
}
rowGetter = (index) => {
return this._rows[index];
};
onRowSelect = (rows) => {
this.setState({ selectedRows: rows });
};
onCellSelected = ({ rowIdx, idx }) => {
this.grid.openCellEditor(rowIdx, idx);
};
onCellDeSelected = ({ rowIdx, idx }) => {
if (idx === 2) {
alert('the editor for cell (' + rowIdx + ',' + idx + ') should have just closed');
}
};
render() {
const rowText = this.state.selectedRows.length === 1 ? 'row' : 'rows';
return (
<div>
<span>{this.state.selectedRows.length} {rowText} selected</span>
<ReactDataGrid
ref={ node => this.grid = node }
rowKey="id"
columns={this._columns}
rowGetter={this.rowGetter}
rowsCount={this._rows.length}
enableRowSelect="multi"
minHeight={500}
onRowSelect={this.onRowSelect}
enableCellSelect={true}
onCellSelected={this.onCellSelected}
onCellDeSelected={this.onCellDeSelected} />
</div>);
}
}
const exampleDescription = (
<div>
<p>Define onCellSelected and onCellDeSelected callback handlers and pass them as props to enable events upon cell selection/deselection.</p>
<p>if passed, onCellSelected will be triggered each time a cell is selected with the cell coordinates. Similarly, onCellDeSelected will be triggered when a cell is deselected.</p>
</div>
);
module.exports = exampleWrapper({
WrappedComponent: Example,
exampleName: 'Cell selection/delesection events',
exampleDescription,
examplePath: './scripts/example21-cell-selection-events.js',
examplePlaygroundLink: 'https://jsfiddle.net/f6mbnb8z/8/'
});
For newer versions,
formatter: ({ row, isCellSelected }) => {
if (isCellSelected) {
console.log(row['{col_name}']);
}
return row['{col_name}']};
}

Resources