Is there a way to pass the data of table as an array of object? - javascript

<img src={xlsImage} onClick={() => exportToExcel(apiListofData, 'users_exits')} style={{ width: "2rem", cursor: 'pointer' }} />
<Table columns={columns} dataSource={apiListofData} pagination={false} rowKey='index' scroll={{ x: 400 }} />
**I am using antd library for table. I am passing the api response (apiListofData) in exportToExcel function. Is there a way to pass table data **

Related

I want to show and hide a form on toggle of a radio button in React js . Im trying how to use react hooks to hide or show a component on onChange even

Now i have used state hook to hide the Form when the page loads. And upon the click or toggle of the radio I'm able to show the Form, But if i toggle the radio again, the form is not hiding.
This is what i have implemented:
const WelcomeTab = () => {
const [toggle, settoggle] = useState(false);
return (
<React.Fragment>
<Tab.Pane
style={{
borderRadius: '7px',
padding: '30px',
}}
attached={false}
>
<Grid>
<Grid.Row>
<Grid.Column floated="left" width={8}>
<Header
style={{
fontSize: '18px',
fontFamily: 'Nunito-Regular',
color: '#4F4F4F',
}}
>
Welcome Screen
</Header>
</Grid.Column>
<Grid.Column floated="right" width={4}>
<Header
as="h4"
style={{
display: 'flex',
justifyContent: 'space-around',
marginLeft: '30px',
}}
>
Customize
<Radio toggle onChange={() => settoggle({ toggle: !toggle })} />
</Header>
</Grid.Column>
</Grid.Row>
</Grid>
{toggle ? (
<Form style={{ paddingTop: '20px' }}>
<Form.Field>
<label style={lableStyle}>Title</label>
<input style={{ marginBottom: '20px' }} />
<label style={lableStyle}>Message</label>
<TextArea />
</Form.Field>
</Form>
) : null}
</Tab.Pane>
</React.Fragment>
);
};
const lableStyle = {
fontFamily: 'Nunito-Regular',
fontWeight: 400,
color: '#4F4F4F',
fontSize: '15px',
display: 'inline-block',
marginBottom: '10px',
};
export default WelcomeTab;
try to add useEffect hook along with change like below,
you no longer need to {} this is old syntax of setState, using hooks we directly make the changes, hope this helps
useEffect(()=>{},[toggle])
replace this wrong syntax code, i can see its not json its boolean value
<Radio toggle onChange={()=>settoggle({toggle: !toggle})}/>
as this is old syntax not work with hooks, try to implment this instead,
<Radio toggle onChange={()=>settoggle(!toggle)}/>

Add a button to react material-table toolbar

I want to add a button to material-table toolbar. it doesnt do anything relevant to the table. it just opens a modal with some information
I want to add a button called "quotations" to the left side of the "add item" button.
Sandbox code: https://codesandbox.io/embed/charming-yalow-4pnk4?fontsize=14&hidenavigation=1&theme=dark
As Will Evers mentioned, it's possible to add whatever is necessary to Toolbar of the MaterialTable component by using Toolbar prop :
Toolbar: (props) => (
<div
style={{
display: "flex",
justifyContent: "flex-end",
alignItems: "center"
}}
>
<Button
style={{ height: "fit-content" }}
color="primary"
variant="contained"
>
Quotations
</Button>
<div style={{ width: "13rem" }}>
<MTableToolbar {...props} />
</div>
</div>
),
Working Demo
Per the docs, it looks like you need to override the Toolbar component of your table and you should be able to add what ever you want above the column headers:
https://material-table.com/#/docs/features/component-overriding
https://i.stack.imgur.com/J0mqf.png
Use this prop in the component tag
renderTopToolbarCustomActions={() => (
<Button
variant="contained"
color="primary"
size="large"
onClick={() => console.log('something')}
>
Quotations
</Button>
)}

Why is this function logging undefined when calling it?

I have a retrieved array of files that have been filtered and put into state.
I can display the files using this:
<List items={this.state.filtPanelMeetFiles.map(file => <div>{file.FileLeafRef}</div>)} onRenderCell={this._onRenderCellFiles} />
and this:
private _onRenderCellFiles = (item) => {
return(
<div>
<tr data-is-scrollable>
<td style={{ width: '150px' }} >{item}</td>
<td style={{ width: '150px' }} >{item.Id}</td>
<td style={{ width: '15px' }}>
<div className={styles.editIcon}><Icon iconName="Delete" id={item.Id} onClick={( this._deleteFile)}/>
</div>
</td>
</tr>
</div>
);
}
I want this function:
public _deleteFile = (ev) => {
const sid = ev;
console.log(sid);
}
To get the id of clicked file, but it's logging undefined. I can see the ID of each file in the array in state but how would I get hold of the ID?
I have identical code in another project but that retrieves items not files. This code works (in the other project) but not in this one. What is different and is the id={item.Id} actually doing anything useful here?
This is what is stored in the filtered state if it helps:
Found it finally!
<div className={styles.editIcon}><Icon iconName="Delete" id={item.Id.toString()} onClick={() => this._deleteFile(item.Id)}/>
<List items={this.state.filtPanelMeetFiles} onRenderCell={this._onRenderCellFiles} />

Is there a way to view a specific item in an already mapped array in React JS?

Im in a bit of a bind here and can use some help. Im mapping over an array of items that I got back from an API call, and I render it to the dom as such:
render() {
const newsItems = this.props.news.map((article) => {
return (
<Row>
<Col xs="auto">
<Card
id={article.id}
style={{
height: "40%",
width: "40%",
border: "solid",
margin: "2rem",
}}
>
<CardImg
top
width="100%"
src={article.urlToImage}
alt="Card image cap"
/>
<CardBody>
<CardTitle>
<strong>{article.title}</strong>
</CardTitle>
<CardSubtitle>Athor: {article.author}</CardSubtitle>
<CardText>{article.description}</CardText>
<Button color="primary" size="lg" active>
View Article
</Button>
</CardBody>
</Card>
</Col>
</Row>
);
});
im having difficulty making the view article button work, to view that one particular mapped article in a separate component, I can't seem to pass the information needed. Any help would be appreciated. Also, if it helps, im using redux. Its just that once its mapped, I can't seem to set that button to know what article is clicked to display the information from the array for that particular article.

How to update react state

I have a list of results from my search output. Each result has an onclick function. I want to display each of the results that the user clicks, and for now I can add each result that the user clicks to an array using this function:
let selectedData = []
function addFunc(resultdata){
console.log(resultdata)
selectedData = [...selectedData, resultdata]
console.log(selectedData)
};
I'm new to React, but I know this isn't the right way and I might have to use states or react hooks. The problem is that because I am using Elasticsearch to output the results, my results are in a function, not the main class. Like this:
class Search extends Component {
render() {
return (
<div>
<ReactiveBase
app="datataglist"
credentials="mRgWyoKGQ:f47be2a6-65d0-43b6-8aba-95dbd49eb882"
url="https://scalr.api.appbase.io"
>
<DataSearch
componentId="search"
dataField={[
"maker_tag_name",
"maker_tag_name.autosuggest",
"maker_tag_name.keyword"
]}
fieldWeights={[6, 2, 6]}
fuzziness={1}
highlightField={["maker_tag_name"]}
placeholder="Search Tag Name"
style={{
marginBottom: 20
}}
title="Maker Tag Name"
/>
<Row gutter={16}>
<Col span={8}>
<MultiList
componentId="system"
dataField="system.keyword"
queryFormat="or"
size={100}
sortBy="asc"
style={{
marginBottom: 20
}}
title="System"
/>
</Col>
<Col span={8}>
<MultiList
componentId="grouping"
dataField="grouping.keyword"
size={100}
style={{
marginBottom: 20
}}
title="Grouping"
/>
</Col>
<Col span={8}>
<MultiList
componentId="unit"
dataField="units.keyword"
size={100}
style={{
marginBottom: 20
}}
title="Unit"
/>
</Col>
</Row>
<SelectedFilters />
<ReactiveList
componentId="results"
dataField="_score"
pagination={true}
react={{
and: ["system", "grouping", "unit", "search"]
}}
size={10}
noResults="No results were found..."
renderItem={RenderItem}
/>
</ReactiveBase>
<div>
</div>
</div>
);
}
}
function getNestedValue(obj, path) {
const keys = path.split(".");
const currentObject = obj;
const nestedValue = keys.reduce((value, key) => {
if (value) {
return value[key];
}
return "";
}, currentObject);
if (typeof nestedValue === "object") {
return JSON.stringify(nestedValue);
}
return nestedValue;
}
function RenderItem(res, triggerClickAnalytics) {
let { unit, title, system, score, proposed, id } = {
title: "maker_tag_name",
proposed: "proposed_standard_format",
unit: "units",
system: "system",
score: "_score",
id: "_id"
};
title = getNestedValue(res, title);
system = getNestedValue(res, system);
unit = getNestedValue(res, unit);
score = getNestedValue(res, score);
proposed = getNestedValue(res, proposed);
id = getNestedValue(res, id);
const resultdata = {id, title, system, unit, score, proposed}
return (
<Row
onClick={triggerClickAnalytics}
type="flex"
gutter={16}
key={res._id}
style={{ margin: "20px auto", borderBottom: "1px solid #ededed" }}
>
<Col style={{ width: "360px" }}>
<h3
style={{ fontWeight: "600" }}
dangerouslySetInnerHTML={{
__html: title || "Choose a valid Title Field"
}}
/>
</Col>
<div style={{ padding: "20px" }} />
<Col>
<p
style={{ fontSize: "1em", width: "300px" }}
dangerouslySetInnerHTML={{
__html: system || "Choose a valid Description Field"
}}
/>
</Col>
<div style={{ padding: "10px" }} />
<Col>
<p
style={{ fontSize: "1em" }}
dangerouslySetInnerHTML={{
__html: unit || "-"
}}
/>
</Col>
<div style={{ padding: "10px" }} />
<Col style={{ minWidth: "120px" }}>
<p
style={{ fontSize: "1em", width: "300px"}}
dangerouslySetInnerHTML={{
__html: proposed || "Choose a valid Description Field"
}}
/>
</Col>
<div style={{ padding: "10px" }} />
<Col>
<p
style={{ fontSize: "1em"}}
dangerouslySetInnerHTML={{
__html: Math.round(score) || "Choose a valid Description Field"
}}
/>
</Col>
<Col>
<Button
shape="circle"
icon={<CheckOutlined />}
style={{ marginRight: "5px" }}
onClick={()=> {addFunc(resultdata)}}
/>
</Col>
</Row>
);
}
Basically, my ReactiveList component is what shows the results. This calls the RenderItem function, which is what displays the data on the screen. In my function, I have a list called resultdata, which contains all the data I need when each result is clicked on. This works, but I need it to display on the screen.
I can't use state, because I have a function. And I can't use hooks because it isn't the main function. Am I doing something wrong? Is there any other alternative to this?
Even if you can't provide a complete answer, I would appreciate any tips on which direction I should look towards.
state is async so it wont update like this:
function addFunc(resultdata){
console.log(resultdata)
selectedData = [...selectedData, resultdata]
console.log(selectedData)
};
and you are using a class so you can't useHooks but setState takes a callback as second argument
function addFunc(resultdata){
console.log(resultdata)
this.setState({selectedData: [...selectedData, resultdata]}, () => console.log(selectedData))
};
so if you continue using a Class approach this will allow you to use setState and utilize the callback in it
there is a callback available too in hooks but it doesn't work quite the same
Place addFunc within the parent component and make your RenderItem function a React Functional component by exporting it. Then provide the addFunc as a function prop from parent component to RenderItem component. That way you can call the function within onClick event. Any of the parent states can be updated from the addFunc. You can supply necessary arguments to the function call as well.

Categories