I am using Ant design in my react project and and want to add the string to the render attribute for the column structure.
Here is a usual code.
import React from 'react';
import ReactDOM from 'react-dom';
import { Table, Divider, Tag } from 'antd';
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: text => <a>{text}</a> // <<<< Want to pass string here
}
];
const data = [
{
key: '1',
name: 'John Brown',
},
{
key: '2',
name: 'Jim Green',
},
{
key: '3',
name: 'Joe Black',
},
];
ReactDOM.render(<Table columns={columns} dataSource={data} />, document.getElementById('container'));
Now in the above code I am passing JSX code in a string to render in column. But I am having string that I want to render.
import React from 'react';
import ReactDOM from 'react-dom';
import { Table, Divider, Tag } from 'antd';
const fun = "text => <a>{text}</a>" // this string I want to render
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: fun // <<<< no passing string here I do know I need to covert this string into something
}
];
const data = [
{
key: '1',
name: 'John Brown',
},
{
key: '2',
name: 'Jim Green',
},
{
key: '3',
name: 'Joe Black',
},
];
ReactDOM.render(<Table columns={columns} dataSource={data} />, document.getElementById('container'));
What approach do I need to follow to run and execute the code which will give me same result as above.
NOTE: I am getting this string from the Back-end
Any help to solve this issue will be appreciated.
You can use the same pattern instead of using as a string like instead of
const fun = "text => <a>{text}</a>"
You can write as:
const fun = text => <a>{text}</a>
Please check the demo at:
.
I solve the issue using the templating language. I have used the squirrelly templating language.
As you see in the below code.
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Table, Divider, Tag } from 'antd';
import * as sqrl from "squirrelly";
const render = "<a>{{data}}</a>"
const htmlNode = (text) =>{
/**
*we are formating a data in the particular format so that
*we can use it along with squirrelly templating
*/
const data = {data : text}
/**
* In the below code we are ,merging the html string and data together
*/
const __html = sqrl.Render(render, data || []);
return <div dangerouslySetInnerHTML={{__html}}/>
}
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: text => htmlNode(text)
}
];
const data = [
{
key: '1',
name: 'John Brown',
},
{
key: '2',
name: 'Jim Green',
},
{
key: '3',
name: 'Joe Black',
},
];
ReactDOM.render(<Table columns={columns} dataSource={data} />, document.getElementById('container'));
Related
I am trying the following code
import React, { Component } from 'react'
import ReactSearchBox from 'react-search-box'
export default class App extends Component {
data = [
{
key: 'john',
value: 'John Doe',
},
{
key: 'jane',
value: 'Jane Doe',
},
{
key: 'mary',
value: 'Mary Phillips',
},
{
key: 'robert',
value: 'Robert',
},
{
key: 'karius',
value: 'Karius',
},
]
render() {
return (
<ReactSearchBox
placeholder="Placeholder"
value="Doe"
data={this.data}
callback={record => console.log(record)}
/>
)
}
}
and it works really. However the search options only show when I start typing in the searchbox. What I am trying to do is when the user clicks in the search, show them some options, Can you help with understanding how to achieve that.
there is a method called
onFocus - A function which acts as a callback when the input is focussed.
which does get called when I click in the search box, but I am not able to work out how to display the options in the dropdown.
import React, { Component } from 'react'
import Select from 'react-select'
export default class App extends Component {
state = {
selectedValue:null
}
data = [
{
label: 'john',
value: 'John Doe',
},
{
label: 'jane',
value: 'Jane Doe',
},
{
label: 'mary',
value: 'Mary Phillips',
},
{
label: 'robert',
value: 'Robert',
},
{
label: 'karius',
value: 'Karius',
},
]
render() {
return (
<Select
options={this.data}
isSearchable
value={this.state.selectedValue}
onChange={this.handleChange}
/>
)
}
}
If you want to display a dropdown with search option I would recommend using react-select library. However your data should be in the form of an object like this {label:' ',value:' '}. This component takes an isSearchable prop that allows us to search the dropdown as well as select an option manually. Hope this helps!
I am trying to figure out why this simple code does not work, it feels like I have done exactly the same thing many times before without errors. What have I done wrong?
import React, {useState} from 'react'
import { MenuItem } from '../menu-item/menu-item.component'
import './directory.styles.scss'
export const Directory = () => {
const sections = [
{
title: 'hats',
imageUrl: 'https://i.ibb.co/cvpntL1/hats.png',
id: 1,
linkUrl: 'shop/hats'
},
{
title: 'jackets',
imageUrl: 'https://i.ibb.co/px2tCc3/jackets.png',
id: 2,
linkUrl: 'shop/jackets'
},
{
title: 'sneakers',
imageUrl: 'https://i.ibb.co/0jqHpnp/sneakers.png',
id: 3,
linkUrl: 'shop/sneakers'
},
{
title: 'womens',
imageUrl: 'https://i.ibb.co/GCCdy8t/womens.png',
size: 'large',
id: 4,
linkUrl: 'shop/womens'
},
{
title: 'mens',
imageUrl: 'https://i.ibb.co/R70vBrQ/men.png',
size: 'large',
id: 5,
linkUrl: 'shop/mens'
}
];
return (
<div className="directory-menu">
{sections.map((title, imageUrl, id) => <MenuItem key={id} title={title} imageUrl={imageUrl}/>)}
</div>
)
}
Error Message:
Error: Objects are not valid as a React child (found: object with keys
{title, imageUrl, id, linkUrl}). If you meant to render a collection
of children, use an array instead.
You are not destructuring properly i.e.
.((title, imageUrl, id) =>
should be
.(({title, imageUrl, id}) =>
Check out this post, it's a common React error.
You could also try something like this
Object.entries(sections).map((x)=>
return x.title;
})
I am using ant design table component and I have selected rows.
I want onClick reset selected rows.
I can not find out where it stores selected rows.
const rowSelection = {
onChange: (selectedRowKeys, rows) => {
this.setState({
selectedRowsArray: [...rows]
});
},
};
<Table rowSelection={rowSelection} columns={columns} dataSource={paymentsHistory} />
Any Idea how to clear selected rows?
rowSelection also takes selectedRowKeys property that will help you control the selected rows at any point in time.
const { selectedRowsArray } = this.state;
const rowSelection = {
selectedRowKeys: selectedRowsArray,
onChange: (selectedRowKeys, rows) => {
this.setState({
selectedRowsArray: [...rows]
});
},
};
<Table rowSelection={rowSelection} columns={columns} dataSource={paymentsHistory} />
Codesandbox Example | Antd Docs
We can also do this with hooks:
import { useState } from 'react';
import { Table, Button } from 'antd';
function App() {
const [selectedRowKeys, setRowKeys] = useState([]);
const [loading, setLoading] = useState([]);
const start = () => {
setRowKeys([]);
};
const onSelectChange = selectedRowKeys => {
setRowKeys(selectedRowKeys);
};
const rowSelection = {
selectedRowKeys,
onChange: onSelectChange,
};
const dataSource = [
{
key: '1',
name: 'Mike',
age: 32,
address: '10 Downing Street',
},
{
key: '2',
name: 'John',
age: 42,
address: '10 Downing Street',
}, enter code here
];
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
];
return (
<div className="App">
<Button type="primary" onClick={start} >
Reload
</Button>
<Table dataSource={dataSource} columns={columns} rowSelection={rowSelection} />;
</div>
);
}
export default App;
Maybe following example will make it clear for you:
import React, { useState } from "react";
import { Table, Button } from "antd";
import "antd/dist/antd.css";
import "./index.css";
export default function App() {
const columns = [
{
title: "Currency",
dataIndex: "сurrency",
key: "сurrency"
}
];
const data = [
{
key: "EUR",
сurrency: "€"
},
{
key: "USD",
сurrency: "$"
},
{
key: "RUB",
сurrency: "₽"
}
];
const [selectedRowsArray, setSelectedRowsArray] = useState([]);
const rowSelection = {
selectedRowKeys: selectedRowsArray,
onChange: (key) => {
setSelectedRowsArray(key);
exchangeMoney(key[0]);
}
};
function exchangeMoney(key) {
console.log(key);
}
return (
<>
<Table
columns={columns}
dataSource={data}
rowSelection={{ type: "radio", ...rowSelection }}
/>
<Button className="clear-btn" onClick={() => setSelectedRowsArray([])}>
CLEAR
</Button>
</>
);
}
see in codesandbox
React tables Calculating Footer sum on page change on Sort on search, how can we achieve that.
import React from "react";
import { render } from "react-dom";
import ReactTable from "react-table";
import "react-table/react-table.css";
const data = [
{
id: 1,
product: "apple",
stock: 1,
price: 123
},
{
id: 2,
product: "pie",
stock: 2,
price: 22
}
];
const App = () => (
<div>
<ReactTable
data={data}
columns={[
{
Header: "Id",
accessor: "id"
},
{
Header: "Product",
accessor: "product",
Footer: "Summary"
},
{
Header: "Stock",
accessor: "stock"
},
{
Header: "Price",
accessor: "price",
Footer: (
<span>{
data.reduce((total, { price }) => total += price, 0)
}</span>
)
}
]}
defaultPageSize={2}
/>
</div>
);
above code can be used to get the sum of a column data of all the rows, can anyone please guide me in a right way.
Import this first:
import _ from "lodash";
Then below code should resolve your issue:
{
Header: "Price",
accessor: "price",
id: "price"
Footer: <span>{_.sum(_.map(data, d => d.price))}</span>
)
}
Please note that there should be underscore symbol between { and .sum.
Similarly underscore symbol between ( and .map
Somehow it is removed when I posted my code here.
Can you please suggest me how to update the data in the grid. I am updating the data on the server request. How do re-render the data table? In the render section, I have used react Table component. Can you please suggest me the actual approach to use this react table component>
import React, { PureComponent } from 'react';
import ReactTable from 'react-table'
import "./Vendors.css";
export default class VendorsList extends PureComponent {
data = [{
name: 'Tanner Linsley',
age: 26,
friend: {
name: 'Jason Maurer',
age: 23
}
}];
columns = [{
Header: 'Name',
accessor: 'name' // String-based value accessors!
}, {
Header: 'Age',
accessor: 'age',
Cell: props => <span className='number'>{props.value}</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'
}];
constructor(props) {
super(props);
fetch("http://api.com/vendor/list", {
method : 'POST'
})
.then(res => res.json())
.then(
(result) => {
this.data = [{
name: 'Tanner Linsley',
age: 290,
friend: {
name: 'Maurer',
age: 23
}
}];
}
)
}
render() {
return
<div>
<div className="gridsize"><ReactTable data={this.data} columns={this.columns} /></div>
</div>
}
}
Raja
you need to use states..
and call setState when you get response from your server. calling the setState function will call render function automatically
When you want to update the view based on a change in data, you should store the data in state and update it using setState which will trigger a re-render and update the view. Also API request must be handled in componentDidMount lifecycle function and not constructor
export default class VendorsList extends PureComponent {
state = {
data = [{
name: 'Tanner Linsley',
age: 26,
friend: {
name: 'Jason Maurer',
age: 23
}
}];
}
columns = [{
Header: 'Name',
accessor: 'name' // String-based value accessors!
}, {
Header: 'Age',
accessor: 'age',
Cell: props => <span className='number'>{props.value}</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'
}];
componentDidMount() {
fetch("http://api.com/vendor/list", {
method : 'POST'
})
.then(res => res.json())
.then((result) => {
this.setState({data: [{
name: 'Tanner Linsley',
age: 290,
friend: {
name: 'Maurer',
age: 23
}
}]
});
)};
}
render() {
return (
<div>
<div className="gridsize"><ReactTable data={this.state.data} columns={this.columns} /></div>
</div>
)
}
}