Display the selected item to another component using react hooks - javascript

I have a section in which contains templates, now I want a user to select one of the templates and edit the data in templates eg name, job title, contact etc.
Here is my live demo in code sandbox editor live demo
Here is templates.js
export default function Templates() {
const [selected, setSelected] = useState("");
let history = useHistory();
const handleSelected = (e) => {
const value = e.target.innerHTML;
setSelected(value);
history.push('/Settings')
};
return (
<div className="App">
<h2>Select one of the Template below by clicking title</h2>
<div className={`template_one ${selected === "Template_one" ? "selected" : "unselected"}`} onClick={(e) => {setSelected(selected !== "Template_one" ? "Template_one" : ""); handleSelected(e);}}>
<h1>Template_one</h1>
<table striped bordered hover size="sm">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Job</th>
<th>Facebook</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<th>Developer</th>
<td>facebook/Mark</td>
</tr>
</tbody>
</table>
</div>
<div className={`template_two ${selected === "Template_two" ? "selected" : "unselected"}`} onClick={(e) => {setSelected(selected !== "Template_two" ? "Template_two" : "");handleSelected(e);}}>
<h1>Template_two</h1>
<table striped bordered hover size="sm">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Job</th>
<th>Company</th>
<th>Contact </th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Trump</td>
<th>President</th>
<td>Trump Organization</td>
<td>+1 728 256 345</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
And here is settings.js
import React from "react";
export default function Settings() {
return (
<div>
<h1>Settings</h1>
<div className="Settings">
<form>
Name: <input type="text" name="firstname" />
Job: <input type="text" name="job" /> <br />
Facebook: <input type="text" name="facebook" />
Company: <input type="text" name="company" />
Contact: <input type="text" name="contact" />
</form>
<div className="selected-template">
Here should be the selected template
</div>
</div>
</div>
);
}
Expected result:
Problem: I don't know how to display the selected templates in the settings component.
How do I copy the selected template to the settings component so that the user can edit the selected template.?

I don't know why but someone deleted my other post that's why I'm seeing your message now. If you want to make different styles you can add classnames to your data. Also if you want, you can look at this libary: https://material-ui.com/styles/basics/ it is so populer around react users. You can basicly make all styles in javascript with this libary. If you gonna use this libary you can add all jss in your data.
here is example:
const table1= {
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
},
};
Data=[
{
name:'something',
style:table1
},
{
age:22,
style:table2
}
]
and basic explanation about how to use this styles
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
function Table() {
const classes = props.data.style();
return <Table className={classes.root}>Your table here</Table>;
}
export default withStyles(props.data.style)(Table);

Related

Export checked element as csv file

I'm trying to get only checked items saved in an array So that I'm going to export it as a CSV file. need help, that's my sandbox below;
https://codesandbox.io/s/laughing-bush-5fvl7b?file=/src/App.js
You can save the selected items id in state. Have a look:
import { useState } from "react";
import { CategoriesData } from "../data";
import "./styles.css";
export default function App() {
const [selectedIds, setSelectedIds] = useState([]);
return (
<div className="App">
<table id="categories">
<thead>
<tr id="titres">
<td className="input-check">
<input type="checkbox" className="checkbox" />
</td>
<td>CATEGORIES</td>
<td>DESCRIPTION</td>
</tr>
</thead>
<tbody>
{CategoriesData.map((category, index) => (
<tr
id={`element-${index}`}
key={category._id}
className={
selectedIds.includes(category.id) ? "product active" : "product"
}
>
<td className="input-check">
<input
type="checkbox"
className="checkbox"
onClick={(e) => {
var selected = e.target.checked;
if (selected) {
setSelectedIds([...selectedIds, category.id]);
} else {
setSelectedIds([
...selectedIds.filter((x) => x !== category.id)
]);
}
}}
/>
</td>
<td>{category.designation}</td>
<td id="category-desc">{category.description}</td>
</tr>
))}
</tbody>
</table>
</div>

How to define the length of the array when using map function and display the rows which have data?

I have created a button with the collapse effect and In that creating a simple table then I created an excel file and in that created a two table one display the button content and second table display the table content. when I run my code then an unlimited button is created and only 3 buttons display the data which I have stored in the table.
Here is my code:
import React, { useState } from 'react'
import { Table } from 'react-bootstrap'
import * as XLSX from 'xlsx'
import Accordion from './component/accordion'
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faTrashAlt } from '#fortawesome/free-solid-svg-icons'
import './App.css'
function App() {
const[items, setItems] = useState([])
const readExcel=(file) => {
const promise = new Promise((resolve, reject)=>{
const fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);
fileReader.onload=(e)=>{
const bufferArray = e.target.result;
const wb = XLSX.read(bufferArray, {type: "buffer"});
const wsname = wb.SheetNames[0];
const ws = wb.Sheets[wsname];
const data = XLSX.utils.sheet_to_json(ws);
resolve(data);
};
fileReader.onerror=(error) => {
reject(error);
};
});
promise.then((d)=>{
setItems(d);
console.log(d)
});
};
return(
<div className="container-fluid">
<section className="heading">
<h4>Products Details</h4>
<input type="file" className="input-field" name="Upload File" onChange={(e) =>{
const file=e.target.files[0];
readExcel(file);
}} />
</section>
{items.map((d) => (
<Accordion
title={
<tr key={d.ID} className="btn-heading">
<td style={{padding: "0px 36px"}}>{d.ID}</td>
<td style={{padding: "0px 16px"}}>{d.Mail}</td>
<td style={{padding: "0px 67px"}}>{d.Name}</td>
<td style={{padding: "0px 3px"}}>{d.PhoneNo}</td>
<td style={{padding: "0px 98px"}}>{d.City}</td>
<td style={{padding: "0px 6px"}}>{d.Date}</td>
<td style={{padding: "0px 120px"}}>{d.Time}</td>
</tr>
}
content={
<div>
<p className="header">
<span className="header-content">Shipping Address:</span>
292 Naqshband Colony. Near rabbania Mosque. Multan
</p>
<Table size="sm">
<thead>
<tr>
<th>#</th>
<th style={{width:"15%",textAlign:"center"}}>Article No</th>
<th style={{width:"30%"}}>Product Name</th>
<th style={{width:"20%" ,textAlign:"center"}}>Quantity</th>
<th style={{width:"15%" ,textAlign:"center"}}>Price</th>
<th style={{width:"15%" ,textAlign:"center"}}>Total Amount</th>
</tr>
</thead>
<tbody>
{items.map((d) => (
<tr key={d.ArticleNo}>
<colgroup>
<FontAwesomeIcon icon={faTrashAlt} />
</colgroup>
<td>{d.ArticleNo}</td>
<td style={{textAlign:"left"}}> {d.ProductName}</td>
<td>{d.Quantity}</td>
<td>{d.Price}</td>
<td>{d.TotalAmount}</td>
</tr>
))}
</tbody>
</Table>
</div>
}
/>
))}
</div>
);
}
export default App;
And here is my excel file which I have created two tables:
Excel File Tables
here is the output of my project the unlimited buttons:
Code Output

Why am I getting a TypeError when trying to run my code?

I'm trying to figure out why I'm getting Cannot destructure property 'id' of 'this.props.customer' as it is undefined. error. My code seems to be correct from the looks of it but despite this fact, I'm still getting the aforementioned error. Is there something minuscule that I'm overlooking?
Here's CustomerList.js file:
import React, { Component } from "react";
import Customer from "./Customer";
class CustomerList extends Component {
render() {
const customers = this.props.customers;
return(
<div className="data">
<table className="ui celled table">
<thead>
<tr>
<th style={{ width: '50px', textAlign: 'center' }}>#</th>
<th>Name</th>
<th>E-mail</th>
<th style={{ width: '148px' }}>Action</th>
</tr>
</thead>
<tbody>
{
customers.map(customer => {
return <Customer customer={customer} key={customer.id} />;
})
}
<Customer/>
</tbody>
</table>
</div>
);
}
}
export default CustomerList;
Here's Customer.js:
import React, { Component } from 'react';
class Customer extends Component {
render() {
const { id, first_name, last_name, email } = this.props.customer;
return (
<tr>
<td style={{ textAlign: 'center' }}>{id}</td>
<td>{`${first_name} ${last_name}`}</td>
<td>{email}</td>
<td>
<button className="mini ui blue button">Edit</button>
<button className="mini ui red button">Delete</button>
</td>
</tr>
);
}
}
export default Customer;
Below the map part you have a single
<Customer/>
This call to the Customer component has no parameters, so customer is undefined. That is why you get the error.

Getting error "props.data.map is not a function" in React

I am trying to make a form where on submit the data will be displayed in the table below. I have created Form and Table components and passing the form data into Table component. In the table component I have created 2 components; TableHeader and TableBody and passing the data to TableBody from Table. However, I am getting an error:
props.data.map is not a function
Here is my code:
Form.js
import React, { Component } from 'react';
import DisplayTable from '../Components/Table';
import Jumbotron from 'react-bootstrap/Jumbotron';
import Container from 'react-bootstrap/Container';
class Form extends Component {
constructor(){
super();
//1st 3 state fields will fetch the input data and next 3 will store the updated state into it
this.state={
first:'',
last:'',
email:'',
firstU:'',
lastU:'',
emailU:''
};
this.onInputChange=this.onInputChange.bind(this);
this.onInputSubmit=this.onInputSubmit.bind(this);
}
//on input change captures the values of the fields into respective input fields (first,last,email)
onInputChange=(event)=>{
this.setState({
[event.target.name]:event.target.value
}
)
//console.log(event.target.value);
// console.log('input change running');
}
//sets the values on submit
onInputSubmit=()=>{
// this.setState();
//console.log(this.state.first);
this.submitData(this.state.first,this.state.last,this.state.email);
//console.log('input submit running');
}
//sets the onChange state into new state fields
submitData=(first,last,email)=>{
this.setState({
firstU:first,
lastU:last,
emailU:email
});
console.log('submitData running');
}
render() {
return (
<Jumbotron fluid>
<Container>
<h1>Form</h1>
<div className="App" align="center">
<div class="row">
<input
name="first"
onChange={this.onInputChange}
type="text"
value={this.state.first}
/>
</div>
<div class="row">
<input
name="last"
onChange={this.onInputChange}
type="text"
value={this.state.last}
/>
</div>
<div class="row">
<input
name="email"
onChange={this.onInputChange}
type="email"
value={this.state.email}
/>
</div>
<div class="row">
<button name="submit" onClick={this.onInputSubmit}>
Submit
</button>
</div>
</div>
{/*here passed entire state into single variable instead of passing like
this.state.first,this.state.last to reduce code
*/}
<DisplayTable data={this.state}/>
</Container>
</Jumbotron>
);
}
}
export default Form;
Table.js
import React, { Component } from 'react';
import Jumbotron from 'react-bootstrap/Jumbotron';
import Container from 'react-bootstrap/Container';
import Table from 'react-bootstrap/Table';
//props.data will fetch value from the state
class DisplayTable extends Component{
render(){
//console.log("hi"+this.props.data.first);
//const data=this.props;
return (
<Jumbotron fluid>
<Container>
<h1>Data</h1>
<TableHeader/>
<TableBody data={this.props}/>
</Container>
</Jumbotron>
);
}
}
const TableHeader= ()=> {
return(
<div>
<Table striped bordered hover variant="dark">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>email</th>
</tr>
</thead>
</Table>
</div>
);
}
const TableBody = (props)=> {
console.log("k"+props.data.first)
const rows=props.data.map((row,index)=>{
return(
<div>
<Table striped bordered hover variant="dark">
<tbody>
<tr>
<td key={index}></td>
<td>{row.first}</td>
<td>{row.last}</td>
<td>{row.email}</td>
</tr>
</tbody>
</Table>
</div>
);
})
return ({rows});
}
export default DisplayTable;
A good way to go about solving this problem might be to edit your state like so:
this.state = {
users: [
{
first: 'name',
last: 'name',
etc...
},
{
first: 'name',
last: 'name',
etc...
}
],
other: state //if need be
}
This way, you have an array of users and can add more users to the table as needed.
Then you just pass this.state.users to your child component through props.
Is your props.data is an array because map works with array only. I think your data is in {} but not in []. Please verify.
print the data to verify it.

How to properly write a React Class Component that can receive props?

I know how to receive props in presentational components but currently I need to also use functions which have logic therefore I'm needed to change my component into a Class Component right now, I don't know why I'm not able to receive the props.
Here is a part of my component:
class MemberInfoSubPage extends React.Component {
constructor(props) {
super(props);
this.state = {
};
this.renderRow = this.renderRow.bind(this);
}
As you can see, I'm using ES6 & I'm trying to render rows from a map but for now I'm just trying to receive props. Is this code provided correct? I mean the usual syntax.
PS: For additional info, I'm receiving 'props' is not defined. So yea, I'm not receiving the props after changing my component. Previously I was able to receive the props.
EDIT:
import React, {PropTypes} from 'react';
import ons from 'onsenui';
import * as Ons from 'react-onsenui';
class MemberInfoSubPage extends React.Component {
//const result = FlightApi.getAllFlightList();
constructor(props) {
super(props);
this.state = {
};
// this.stateToEntry = this.stateToEntry.bind(this);
this.renderRow = this.renderRow.bind(this);
}
renderRow(row,index) {
const x = 40 + Math.round(5 * (Math.random() - 0.5)),
y = 40 + Math.round(5 * (Math.random() - 0.5));
const names = ['Max', 'Chloe', 'Bella', 'Oliver', 'Tiger', 'Lucy', 'Shadow', 'Angel'];
const name = names[Math.floor(names.length * Math.random())];
return (
<Ons.ListItem key={index}>
<div className='left'>
<img src={`http://placekitten.com/g/${x}/${y}`} className='list__item__thumbnail' />
</div>
<div className='center'>
{name}
</div>
</Ons.ListItem>
);
}
render() {
if (props['index'] == 0) {
return (
<div className="memberInfoSubPage">
<div className="memberInfoSubPage-row1">
<span>{props['data-user'].id}</span>
<table border={1} className="memberInfoSubPage-Table">
<tr>
<th style={{color: 'grey'}}>Rank</th>
<th style={{color: 'grey'}}>Country</th>
</tr>
<tr>
<td>{props['data-user'].rank}</td>
<td>{props['data-user'].country}</td>
</tr>
</table>
</div>
<div>
<div className="memberInfoSubPage2-Summary-Title">Placement Performance Summary</div>
<table border={1} className="memberInfoSubPage-Table2">
<tr>
<td>L</td>
<td>R</td>
</tr>
<tr>
<td>{props['data-user'].placementPerformanceSummary.L}</td>
<td>{props['data-user'].placementPerformanceSummary.R}</td>
</tr>
</table>
</div>
<div>
<div className="memberInfoSubPage2-Summary-Title">Today Detail</div>
<table border={1} className="memberInfoSubPage-Table3">
<tr>
<td>L</td>
<td>R</td>
</tr>
<tr>
<td>{props['data-user'].todayDetail.L}</td>
<td>{props['data-user'].todayDetail.R}</td>
</tr>
</table>
</div>
<div> <table border={1} className="memberInfoSubPage-Table3">
<tr><th style={{color: 'grey'}}>Next Level Upgrade</th></tr>
<tr>
<td>{props['data-user'].nextLevelUpgrade}</td>
</tr>
</table>
</div>
<Ons.Button style={{margin: '6px'}}>Instant Upgrade</Ons.Button>
<div>
<div className="memberInfoSubPage2-Summary-Title" style={{color: 'grey'}}>Conversion Share Platform Portfolio</div>
<table border={1} className="memberInfoSubPage-Table3">
<tr style={{color: 'grey'}}>
<th>Market($)</th>
<th>Unit</th>
<th>Tradable Unit</th>
</tr>
<tr>
<td>{props['data-user'].market}</td>
<td>{props['data-user'].unit}</td>
<td>{props['data-user'].tradableUnit}</td>
</tr>
</table>
</div>
<div><table border={1} className="memberInfoSubPage-Table3">
<tr style={{color: 'grey'}}>
<th>Lock Units</th>
<th>Avg Price</th>
<th>Last Price</th>
</tr>
<tr>
<td>{props['data-user'].lockUnits}</td>
<td>{props['data-user'].avgPrice}</td>
<td>{props['data-user'].lastPrice}</td>
</tr>
</table>
</div>
</div>
);
}
else if (props['index'] == 1) {
return (
<Ons.List
dataSource={[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]}
renderRow={this.renderRow}
renderHeader={() => <Ons.ListHeader>Summary</Ons.ListHeader>}/>
/*<div className="memberInfoSubPage2-Summary-Title">Summary</div>
<table className="memberInfoSubPage2-Summary-Table">
<tr><td>Credit</td><td>{props['data-user'].summary.credit}</td></tr>
<tr><td>Register</td><td>{props['data-user'].summary.register}</td></tr>
<tr><td>CP(S)</td><td>{props['data-user'].summary.cpS}</td></tr>
<tr><td>CP(0)</td><td>{props['data-user'].summary.cp0}</td></tr>
<tr><td>AP</td><td>{props['data-user'].summary.ap}</td></tr>
<tr><td>BO Point</td><td>{props['data-user'].summary.boPoint}</td></tr>
<tr><td>Listed Company Fund</td><td>{props['data-user'].summary.listedCompanyFund}</td></tr>
<tr><td>Promo</td><td>{props['data-user'].summary.promo}</td></tr>
<tr><td>TT</td><td>{props['data-user'].summary.tt}</td></tr>
<tr><td>Re-Entry Point</td><td>{props['data-user'].summary.reEntryPoint}</td></tr>
</table>*/
);
}
else {
return (
<p>Not receiving any index. No content can be shown.</p>
);
}
}
};
MemberInfoSubPage.propTypes = {
'data-pageName': PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
'defaultOption': PropTypes.string,
value: PropTypes.string,
'error': PropTypes.string,
'options': PropTypes.arrayOf(PropTypes.object)
};
export default MemberInfoSubPage;
Here is my code, I'm pretty sure I've missed something.
There is still a lot of unrefined code and the function renderRow & that Onsen list is copy pasted.
props is on the component instance, so you'll need to refer to it as this.props rather than just props in your render function.

Categories