Reputation: 1764
I want to implement validation on react-data-grid table, in which only cells which i defined in the column itself will be validated, and validation only occurs if the state is set to true.
So i have the following codes here
const [ validateMode, setValidateMode ] = useState(false);
const errorBackground = { backgroundColor: 'some error color in here' }
const DescriptionFormatter = props => {
const { value, row } = props;
let template;
if (!validateMode){
template = value;
}
if (validateMode){
let validationStyling = Boolean(value.length) ? {} : errorBackground;
template = <div style={{ ...validationStyling }}>value</div>
}
return template;
}
const tableCols = [
{
key: 'id',
name: 'No'
},
{
key: 'name',
name: 'Name',
editable: !disabled,
editor: <AutoComplete options={nameList} />
},
{
key: 'description',
name: 'Description',
editable: !disabled,
formatter: DescriptionFormatter
}
];
When button is pressed, it will trigger the validateMode state to true, and when that happen, i want the description column to validate the cell and return error background cell if value is empty, otherwise default background if there's value in it (simple checking if value is empty or not).
I can't seem to get the validateMode console log working when i press the button. Its only showing on page init, or when the cell changes (like when inserting value to it).I cannot get the validation working in here, unless if i do it wrongly.
Please help me on this.
Upvotes: 2
Views: 3757
Reputation: 1764
Can't believe im answering my own question lol
Anyway i found the answer already. Validation cannot be done at the columns definition. It has to be done on the cell level of the datagrid. You can pass states to the cell and do your validation there, and change the CSS of the cell by using conditional className to show if validation is true or false.
Snippets of the codes to make it work
import ReactDataGrid, { Row, Cell } from "react-data-grid";
/*
Validator is a state passed from the parent page that indicates whether page is on validation or not, in case
if dev want the table to validate when a trigger hits the page (like submit button?)
*/
const { validator } = props;
const CustomCell = props => {
let valueValidation = false;
if (validator){
/* Insert custom validation in here */
return ( <Cell {...props} className={ validator && valueValidation ? '' : classes.error } /> );
}
/* If not in validation mode, display normal rows */
if (!validator){
return ( <Cell {...props} /> );
}
}
const CustomRow = props => {
return ( <Row {...props} cellRenderer={cellProps => <CustomCell {...cellProps} />} /> );
}
return (
<ReactDataGrid
rowRenderer={CustomRow}
/>
);
Upvotes: 5