React-Table: How to change the background color of a row if it is clicked (selected) with the mouse? - react-table

I have the following code for retrieving data of the clicked row:
<ReactTable
getTdProps={(state, rowInfo, column, instance) => {
return {
onClick: (e, handleOriginal) => {
if (typeof rowInfo !== "undefined") this.rowClick(rowInfo.row.RecipeName);
if (handleOriginal) {
handleOriginal()
}
}
}
}}
How can I change the background color of the clicked row? Or what is the best way to highlight the clicked row?

Please see here for an answer: Select row on click react-table
Here is my code:
First of all you need a state:
this.state = {
selected: -1
};
-1 is important because otherwise the row with the index 0 will be highlighted without clicking on it.
And getTdProps looks like this:
getTrProps={(state, rowInfo, column, instance) => {
if (typeof rowInfo !== "undefined") {
return {
onClick: (e, handleOriginal) => {
this.setState({
selected: rowInfo.index
});
if (handleOriginal) {
handleOriginal()
}
},
style: {
background: rowInfo.index === this.state.selected ? '#00afec' : 'white',
color: rowInfo.index === this.state.selected ? 'white' : 'black'
},
}
}
else {
return {
onClick: (e, handleOriginal) => {
if (handleOriginal) {
handleOriginal()
}
},
style: {
background: 'white',
color: 'black'
},
}
}
}}

Related

SwiftUI button - only right side tappable

I have the following SwiftUI view which is essentially a textfield containing a button:
var body: some View {
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: Constants.cornerRadius, style: .continuous)
.stroke(isFocused ? Color.blue : hasWarning ? .blue : .gray, lineWidth: Constants.lineWidth)
HStack {
Text(title)
.font(.bodyFont)
.foregroundColor(isFocused ? Color.blue : hasWarning ? .red : .gray)
.padding(.horizontal, text.isEmpty ? Constants.Padding.horizontalIsEmpty : Constants.Padding.horizontalIsNotEmpty)
.background(text.isEmpty ? Color.clear : background)
.padding(.leading, Constants.Padding.leading)
.offset(y: text.isEmpty ? Constants.Offset.isEmpty : -(frameHeight / Constants.Offset.isNotEmptyRatio))
.scaleEffect(text.isEmpty ? Constants.ScaleEffect.isEmpty : Constants.ScaleEffect.isNotEmpty, anchor: .leading)
if let button = button {
Spacer()
Button(action: {
button.action()
}, label: {
Text(button.labelText)
})
.padding(.trailing, Constants.Button.trailingPadding)
}
}
TextField("", text: $text, onEditingChanged: { inFocus in
self.isFocused = inFocus
})
.font(.bodyFont)
.padding(.horizontal, Constants.Padding.horizontal)
}
.frame(height: frameHeight)
.background(background)
.animation(.easeInOut(duration: Constants.Animation.easeInOut))
.padding(.top, Constants.Padding.top)
}
The result is a field like this:
However, only the very right hand side of the button is tappable.
I have tried adding a contentShape, like this:
if let button = button {
Spacer()
Button(action: {
button.action()
}, label: {
Text(button.labelText)
})
.contentShape(Rectange())
.padding(.trailing, Constants.Button.trailingPadding)
}
However this has made no difference. Wondering where I'm going wrong here.
Found the issue! It was a simple mistake.
The HStack including the button needed to be wrapped around this element:
TextField("", text: $text, onEditingChanged: { inFocus in
self.isFocused = inFocus
})
.font(.bodyFont)
.padding(.horizontal, Constants.Padding.horizontal)
Previously what was happening was that this element was overlapping the button, obscuring the tappable area. So the correct code would be:
HStack {
TextField("", text: $text, onEditingChanged: { inFocus in
self.isFocused = inFocus
})
.font(.bodyFont)
.padding(.horizontal, Constants.Padding.horizontal)
if let button = button {
Spacer()
Button(action: {
button.action()
}, label: {
Text(button.labelText)
})
.padding(.trailing, Constants.Button.trailingPadding)
}
}

filter by category work not properly with remote search?

Hello I have problem compute vue filter by category it work not properly when I add item on Service tab and then click on Medicine tab remote search item by category it will stuck and filter not work and when I click in Service tab back it show only number 2.
this my template
<el-table
:data="itemFilters"
row-key="no"
style="width: 100%"
>
This my script
computed: {
itemFilters() {
const self = this
let item = self.form.items.filter(o => {
return o.categoryName === self.tabActive || o.itemId === ''
})
return item
},
},
this Method
methods: {
_getItemOpts(query, type) {
let exp = new RegExp(query)
let selector = {
$or: [
{ name: { $regex: exp, $options: 'i' } },
{ refNo: { $regex: exp, $options: 'i' } },
{ barcode: { $regex: exp, $options: 'i' } },
],
activityType: { $in: ['Sale'] },
status: 'Active',
'catDoc.name': this.tabActive,
}
// For form Sale Return and receipts refund
if (this.formName == 'Sale_Return' || this.formName == 'Receipt_Refund') {
selector.itemType = { $ne: 'Bundle' }
}
findItems
.callPromise({ selector: selector })
.then(result => {
// this.itemOpts = result
if (type == 'remote') {
// For remote
this.form.items[this.activeIndex].itemOpts = result
} else {
// For scan barcode
let item = result[0]
if (item) {
let row = {
itemId: item._id,
itemType: item.itemType,
memo: '',
qty: 1,
qtyRate: 1,
unitId: item.units[0].unitId,
units: item.units,
price: item.price,
amountBeforeDiscount: item.price,
discountRate: 0,
discountValue: 0,
amountAfterDiscount: item.price,
taxId: '',
taxAmount: 0,
// For expand bundle item
subItems: [],
expand: 'expand',
// For sales only(cash sales and invoice)
// refSaleOrderId: '',
// refSaleOrderDetailId: '',
// refNo: '',
itemOpts: result,
}
this.form.items.push(row)
} else {
Notify.warning({ message: 'This item do not set barcode!' })
}
}
this.loading = false
})
.catch(err => {
this.loading = false
this.$notify.error(err.reason)
})
},
}
Please help...

Change font size and font color in Chartjs Angular 5

Font color in chartjs is light gray, then when you want to print from page, it does not appear.
I change the font color of chartjs in options attribute, but it does not work.
How can I change the font color in chartjs angular
public options:any = {
legend: {
labels: {
// This more specific font property overrides the global property
fontColor: 'red',
fontSize: '30'
}
}
};
in template :
<canvas baseChart
height=100
[datasets]="barChartData"
[labels]="barChartLabels"
[options]="barChartOptions"
[legend]="barChartLegend"
[colors]="chartColors"
[chartType]="barChartType"
[options]="options"
>
</canvas>
I use chartjs like following in ts file.
This is my complete ts file:
import { Component, Input, OnInit } from '#angular/core';
import { Test } from './models/test.model';
#Component({
selector: 'app-customer-report-test',
templateUrl: './customer-report-test.component.html',
styleUrls: ['./customer-report-test.component.css']
})
export class CustomerReportTestComponent implements OnInit {
#Input('test') test: Test = new Test();
public barChartOptions:any = {
scaleShowVerticalLines: false,
responsive: true
};
public barChartLabels:string[];
public barChartType:string = 'bar';
public barChartLegend:boolean = true;
public barChartData:any[];
backgroundColorList: string[];
public chartColors: any[] = [
{
backgroundColor: this.backgroundColorList
}];
public options:any;
constructor() { }
//----------------------------------------------------------------------------
ngOnInit() {
//set Label
this.barChartLabels = [];
for(let i=1; i<= this.test.data_array.length; i++){
this.barChartLabels.push('' + i);
}
//set data chart
this.barChartData = [{data: this.test.data_array, label: this.test.test_type[1]}]
this.test.test_type[1]}, {data: [20,20, 20, 20],type: "line",label: ['0', '1', '2', '3'] ,fill:'none'}]
// set color to line according to state_array
this.backgroundColorList = [];
if(this.test.state_array.length != 0){
for(let i=0; i<this.test.data_array.length; i++){
if(this.test.state_array[i] == 0){
this.backgroundColorList.push('#069ed6');
}else if(this.test.state_array[i] == 1){
this.backgroundColorList.push('#F5482D');
}else if(this.test.state_array[i] == 2){
this.backgroundColorList.push('#CAC409');
}
}
}
else{
for(let d of this.test.data_array){
this.backgroundColorList.push('#069ed6');
}
}
this.chartColors = [
{
backgroundColor: this.backgroundColorList
}];
this.options = {
responsive: true,
title: {
display: true,
text: 'Custom Chart Title'
},
legend: {
display: true,
labels: {
fontColor: 'red'
}
}
};
}
}
for changing the color of numbers and lines in coordinate plane,we can do:
for example in xAxes:
xAxes: [{
gridLines: {
display: true,
color: "red" // this here
},
ticks: {
fontColor: "red", // this here
}
}],
and font and color of labels:
legend: {
display: true,
labels:{
fontSize: 10,
fontColor: 'red',
}
},
DEMO.
You may try to edit the source code.
1. Go to the link /node_modules/chart.js/src/core/core.js in your node modules folder.
2. edit the following code i.e the core.js file. change the
defaultFontColor: '#0000ff'
to any color you want. I have implemented this in my code for pie chart. and it worked.
`
defaults._set('global', {
responsive: true,
responsiveAnimationDuration: 0,
maintainAspectRatio: true,
events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
hover: {
onHover: null,
mode: 'nearest',
intersect: true,
animationDuration: 400
},
onClick: null,
defaultColor: 'rgba(0,0,0,0.1)',
defaultFontColor: '#0000ff',
defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
defaultFontSize: 12,
defaultFontStyle: 'normal',
showLines: true,
// Element defaults defined in element extensions
elements: {},
// Layout options such as padding
layout: {
padding: {
top: 0,
right: 0,
bottom: 0,
left: 0
}
}
});
module.exports = function() {
// Occupy the global variable of Chart, and create a simple base class
var Chart = function(item, config) {
this.construct(item, config);
return this;
};
Chart.Chart = Chart;
return Chart;
};`

How to change CSS of columns - ReactTable

I am using react-table in my application.
I am stuck in doing one thing i.e. changing the CSS of columns while a column is being resized.
Currently when you resize a column only cursor changes. What I want is to add border to the selected column.
I searched for this on SO and google as well. But couldn't find anything useful. And In the documentation as well nothing is mentioned about this topic as well.
Update
Now I am able to add border while dragging the column while resizing. I am able to do so by adding and removing the class.
What I did to do so:
Created a var in the state for className:
this.state = {
addBorder: null
}
Passed this class name in my column:
const columns = [{
Header: 'Name',
accessor: 'name', // String-based value accessors!,
headerClassName: this.state.addBorder,
className: this.state.addBorder
}, {
Header: 'Age',
accessor: 'age',
Cell: props => <span className='number'>{2}</span> // Custom cell components!
}, {
id: 'friendName', // Required because our accessor is not a string
Header: 'Friend Name',
accessor: d => d.friend.name // Custom value accessors!
}, {
Header: props => <span>Friend Age</span>, // Custom header components!
accessor: 'friend.age'
}];
return (
<div onMouseUp={this.handleMouseUp}>
<ReactTable
data={data}
columns={columns}
resizable={true}
onResizedChange={(col, e) => {
const column = col[col.length-1];
this.setState({addBorder: column.id})
}} />
</div>
)
}
To remove the class when dragging ends:
handleMouseUp (e) {
this.setState({addBorder: null});
}
But I am still not able to add border on hover.
Now, I am sending my custom HTML in header props. And in my HTML I have made an extra div. And I have moved this div to right. And on hover of this div, I am emitting mouse events and changing CSS accordingly.
But Existing div in the header that is responsible for resizing column is overlapping with my Div.
Header: props => <div className='header-div'> Name <div onMouseOver = {() => {
console.log('mose');
this.setState({className: 'addBorder'});
}} className='hover-div' onMouseOut = {() => {console.log('sdasd');this.setState({className: null});}}> </div></div> ,
From what I understand, you want to add some border when you hover over a column header. If my understanding is correct, you can use :hover pseudo selector over the header class
.hdrCls:hover {
border: 2px solid rgba(0,0,0,0.6) !important;
}
Update :
You can manipulate state in onResizedChange handler exposed by react-table
onResizedChange={(newResized, event) => {
let resizedCol = newResized.slice(-1)[0].id;
if(this.state.activeCol !== resizedCol) {
this.setState({
activeCol: resizedCol,
resizing: true
})
}
}}
Also, make sure you have to make the resizing state to false on mouseup event. For that I have come up with the below solution.
componentDidUpdate(props, state) {
if (this.state.resizing && !state.resizing) {
document.addEventListener('mouseup', this.onMouseUp);
} else if (!this.state.resizing && state.resizing) {
document.removeEventListener('mouseup', this.onMouseUp);
}
}
onMouseUp = (evt) => {
this.setState({
activeCol: '',
resizing: false
});
evt.stopPropagation();
evt.preventDefault();
}
For reference:
const ReactTable = window.ReactTable.default
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
activeCol: '',
resizing: false
}
}
componentDidUpdate(props, state) {
if (this.state.resizing && !state.resizing) {
document.addEventListener('mouseup', this.onMouseUp);
} else if (!this.state.resizing && state.resizing) {
document.removeEventListener('mouseup', this.onMouseUp);
}
}
onMouseUp = (evt) => {
this.setState({
activeCol: '',
resizing: false
});
evt.stopPropagation();
evt.preventDefault();
}
render() {
const data = [{
name:"Mark",
age:24
},
{
name:"Derek",
age:26
}]
const columns = [{
Header: 'Name',
accessor: 'name', // String-based value accessors!,
headerClassName: 'hdrCls',
className: (this.state.activeCol === 'name') && this.state.resizing ? 'borderCellCls' : 'defaultCellCls'
}, {
Header: 'Age',
accessor: 'age',
headerClassName: 'hdrCls',
className: (this.state.activeCol === 'age') && this.state.resizing ? 'borderCellCls' : 'defaultCellCls'
}];
return <ReactTable
data = { data }
columns = { columns }
showPagination= {false}
onResizedChange={(newResized, event) => {
let resizedCol = newResized.slice(-1)[0].id;
if(this.state.activeCol !== resizedCol) {
this.setState({
activeCol: resizedCol,
resizing: true
})
}
}}
/>
}
}
ReactDOM.render( < App / > , document.getElementById("app"))
.hdrCls:hover {
border: 2px solid rgba(0,0,0,0.6) !important;
}
.borderCellCls {
border-right: 2px solid rgba(0,0,0,0.6) !important;
border-left: 2px solid rgba(0,0,0,0.6) !important;
}
.defaultCellCls {
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-table/6.7.6/react-table.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/react-table/6.7.6/react-table.css"></link>
<div id="app"></div>
You can play around with CSS. Hope this is what you want and hope this helps.
Update:
I think you have to play with CSS to achieve what you desire.
.borderCellCls {
border-right: 2px solid rgba(0,0,0,0.6) !important;
border-left: 2px solid rgba(0,0,0,0.6) !important;
}
If you are here to find out how to set className to a column cell (with the react-table), here is the solution:
1)
<tr
{...row.getRowProps()}
>
{row.cells.map((cell) => (
<td
{...cell.getCellProps([
{
className: cell.column.className, // pay attention to this
style: cell.column.style,
// set here your other custom props
},
])}
>
{cell.render('Cell')}
</td>
))}
</tr>
2)
const columns = React.useMemo(
() => [
{
Header: 'Date',
accessor: 'date',
minWidth: 70,
className: 'text-dark fw-bolder fs-6 min-w-70px', // pass className props here
headerClassName: 'text-muted', // or another props like this one
}]
<Table columns={columns} ... />
And finally, those props will be passed to your cells
For TypeScript support follow the instructions in DefinitelyTyped, ie. create the file /src/types/react-table-config.d.ts with the content from the instructions, then add the following to it to support custom properties on your column (add more properties in the last line as required):
// Added to support classes to template from:
// https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react-table
export interface ColumnInstance<
D extends Record<string, unknown> = Record<string, unknown>
> extends Omit<ColumnInterface<D>, 'id'>,
ColumnInterfaceBasedOnValue<D>,
UseTableColumnProps<D>,
Record<headerClassName | className, string> {}

Raphael JS Free Transform a Class or ID

I have some difficulties and would like your help.
I want to apply a FreeTransform in some objects with a particular class or id.
For example ... Within my HTML, I want to put an image gallery. And I would like the script freetransform apply to all images that have a specific class.
I have an example of what I did so far.
var r = Raphael(document.getElementById('workspace'));
var img = r.image('http://www.porcopedia.com/images/thumb/Simbolo_Goi%C3%A1s.jpg/600px-Simbolo_Goi%C3%A1s.jpg', 10, 10, 200, 200);
register(img);
function register(el) {
el.data('dragged', false);
el.click(function() {
// Toggle handles on click if no drag occurred
if ( !this.data('dragged') ) {
if ( this.freeTransform.handles.center === null ) {
this.toFront();
this.freeTransform.showHandles();
} else {
this.freeTransform.hideHandles();
}
}
});
r.freeTransform(el, {attrs: {
fill: 'black',
stroke: '#111'
}, drag: true,
keepRatio: ['axisX', 'axisY','bboxCorners'],
size: 6,
scale: [ 'axisX', 'axisY', 'bboxCorners', 'bboxSides' ],
rotate: true,
draw: ['bbox', 'circle']}, function(ft, events) {
if ( events.indexOf('drag start') !== -1 ) {
el.data('dragged', false);
}
if ( events.indexOf('drag') !== -1 ) {
el.data('dragged', true);
}
}).hideHandles();
}
Example JSFIDDLE

Resources