Import child component to use in a html table structure - reactjs

I want to import a component with a child component using specified HTML markup
I am almost there I guess, but I have some problem with the exporting. Added som more data.
usingTable.js
import React, { Component } from "react";
import tableHeader from ".components/data/tableHeader.json";
import Rows from ".components/data/rows.json";
import Table, {Row} from "./components/table.js";
class UsingTable extends Component {
render() {
return(
<>
<Table tableHeader={TableHeader} rows={Rows}>
<Row>
<td colSpan="2">A</td>
<td>B</td>
<td>C</td>
</Row>
</Table>
</>
);
}
}
export default UsingTable;
I don't know if this is the right setup. Maybe someone can give me a hand on this?
table.js
import React, { Component } from "react";
class Table3 extends Component {
render() {
const tableHeader = this.props.tableHeader.map((col,i) => (
<th>
{col}
</th>
))
const row1 = this.props.row.map((row,i) => (
<td>
{row}
</td>
))
return (
<table>
<thead>
<tr>
{tableHeader}
</tr>
</thead>
<tbody>
{Row1}
{Row}
</tbody>
</table>
)
}
}
export default Table3;
export const Row = props => {
return <tr>{props.children}</tr>
}
I want the result to be
<table>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<!-->
<tr>
<td colSpan="2">A</td>
<td>B</td>
<td>C</td>
</tr>
<!-->
</tbody>
</table>```

In your UsingTable your passing 2 props (tableHeader and rows) and 1 child (Row)
Then, in your Table3 component your mapping over tableHeader, which is a valid prop and over this.props.rows which doesn't look like its defined (row should be called rows)
If you want to use the Row child that you passed in, you need to access it using this.props.children
For example, stick {this.props.children} underneath {Row}. Hope that helps

Related

Add a class to a row when a table has a specified text

I saved my data from a database in a json and then imported the data into a table.
Now my question is how can i add a class to a row when the name field has a specified value.
I would like to color a complete row of this table if the Name column has a specified value.
Like if the name field contain "hallo" i want that the completly row is in blue.
import React, { useState } from "react";
import data from "../data.json";
const App = () => {
const [contacts, setContacts] = useState(data);
return (
<div className="app-container">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Adress</th>
<th>Country</th>
</tr>
</thead>
<tbody>
{contacts.map((contact)=> (
<tr>
<td>{contact.id}</td>
<td>{contact.name}</td>
<td>{contact.adress}</td>
<td>{contact.country}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
export default App;
Try adding an inline style and adding a ternary condition you can check whether you want that row to be styled or not.
If you want to add more style to that row just add more css in the styles object
import React, { useState } from "react";
import data from "./data.json";
const styles = { backgroundColor: "blue" };
const App = () => {
const [contacts, setContacts] = useState(data);
return (
<div className="app-container">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Adress</th>
<th>Country</th>
</tr>
</thead>
<tbody>
{contacts.map((contact) => (
<tr style={contact.name === "hallo" ? styles : null}>
<td>{contact.id}</td>
<td>{contact.name}</td>
<td>{contact.adress}</td>
<td>{contact.country}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default App;
If you have a CSS file then just use ternary condition inside className instead of style in .
just add your condition where you wanna specify the className or inline style like this :
{contacts.map((contact)=> (
<tr className={contact.name.includes("hallo") ? "blue" : "red"}>
<td>{contact.id}</td>
<td>{contact.name}</td>
<td>{contact.adress}</td>
<td>{contact.country}</td>
</tr>
))}

Frontend page doesn't display unless i comment out my table making code

Here is my code. I used typescript and my database is in a .json file. My page displays fine when I don't try to display the table and disappears completely
import React, { useState } from "react";
import "./viewAvailableShifts.css";
import "bootstrap/dist/css/bootstrap.min.css";
import MockData from "./data.json";
export class ViewAvailableShifts extends React.Component {
render() {
const [data] = useState(MockData);
return (
<>
<div className="row">
<div className="leftcolumn">
<div className="center">
<h1>Available Shifts</h1>
<div>
<table>
<thead>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
{data.map((d) => (
<tr key={d.id}>
<td>{d.first_name}</td>
<td>{d.last_name}</td>
<td>{d.email}</td>
<td>{d.gender}</td>
</tr>
))}
</tbody>
</table>
</div>
Have you tried mapping the table rows outside of the return? Also wondering why data was in square brackets? Maybe curley braces or none at all, depending on how you return it from state? so if it's already an array just data if you need to make it an array maybe spread [...data]?
export class ViewAvailableShifts extends React.Component {
render() {
const data = useState(MockData)
const rows = data.map((d) => (
<tr key={d.id}>
<td>{d.first_name}</td>
<td>{d.last_name}</td>
<td>{d.email}</td>
<td>{d.gender}</td>
</tr>
))
return (
<>
<div className="row">
<div className="leftcolumn">
<div className="center">
<h1>Available Shifts</h1>
<div>
<table>
<thead>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>{rows}</tbody>
</table>
</div>
</div>
</div>
</div>
</>
)
}
}
Hooks doesn't work inside class component
import React, { useState } from "react";
import "./viewAvailableShifts.css";
import "bootstrap/dist/css/bootstrap.min.css";
import MockData from "./data.json";
export const ViewAvailableShifts = () => {
const [data] = useState(MockData);
return (
<>
<div className="row">
<div className="leftcolumn">
<div className="center">
<h1>Available Shifts</h1>
<div>
<table>
<thead>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
{data.map((d) => (
<tr key={d.id}>
<td>{d.first_name}</td>
<td>{d.last_name}</td>
<td>{d.email}</td>
<td>{d.gender}</td>
</tr>
))}
</tbody>
</table>
</div>
What are you trying to accomplish with useState? useState is a hook that listens for changes to data and then changes the UI accordingly. Use state returns two values though, it would be used like this...
const [data, setData]= useState(someDataOrEmptyValueButNeverActuallyEmpty)
onSomeEvent((eventOrDataOrWhatNot) => setData(eventOrDataOrWhatNot))
and then whatever in your UI that was depending on data will adjust to the new values.
So, are you ready?You can't us hooks in class components
export const ViewAvailableShifts = () => {
const [data] = useState(MockData);
‏}
Should be
export default class ViewAvailableShifts extends Component {
constructor() {
super();
this.state: {data: MockData}
}
render(){...}
}

I tried simple print function using react-to-print. Parsing error: Unexpected token, expected ","

I tried to print simple table using react-to-print. I got
Parsing error: Unexpected token, expected "," at line no 24 "const".
I am new to react.
import React, { Component } from 'react';
import ReactToPrint, { PrintContextConsumer } from 'react-to-print';
import { ComponentToPrint } from './ComponentToPrint';
export default class Form extends Component {
render() {
return (
<table>
<thead>
<th>column 1</th>
<th>column 2</th>
<th>column 3</th>
</thead>
<tbody>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
</tr>
</tbody>
</table>
const Example = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
return (
<div>
<ComponentToPrint ref={componentRef} />
<button onClick={handlePrint}>Print this out!</button>
</div> );
}
}
}
Sorry for necro posting, but since the answer is missing, let's fix this!
Here your Form is what should be used in place of ComponentToPrint, and of course it must be separate from your Example functional component.
That's how it is!
To explain in more details, you should have two jsx (as an example):
form.jsx
--------
import React, { Component } from 'react';
export default class Form extends Component {
render() {
return (
<table>
<thead>
<th>column 1</th>
<th>column 2</th>
<th>column 3</th>
</thead>
<tbody>
<tr>
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
</tr>
</tbody>
</table>
);
}
}
-- this is your "component to print" (i.e. it returns what will be printed out).
And also you need
example.jsx
-----------
import Form from './form';
import React, { useRef } from 'react';
import { useReactToPrint } from 'react-to-print';
const Example = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
return (
<div>
<Form ref={componentRef} />
<button onClick={handlePrint}>Print this out!</button>
</div>
);
}
-- this is your component (functional component) with "Print this out!" button which takes ref to your Form as the content for printing.
All that's left is to use your Example somewhere in the App, it will produce the table and a button, clicking the button will call printer dialogue.

Warning: Each child in a list should have a unique "key" prop. when create table structure

I am new to react and face this type of error related to key in this table structure.
in this code, we create table for fetch employee data fro particular API and display it in table formate but for id, there is some missing in code I read so many solutions for that but I don't what is a change in core .
import React,{Component} from 'react';
import {Table} from 'react-bootstrap';
class EmployeeList extends Component{
constructor(props){
super(props);
this.state = {emps:[]}
}
componentDidMount(){
this.refreshList();
}
refreshList(){
fetch('https://localhost:44339/api/employee')
.then(response=> response.json())
.then(data => {
this.setState({emps:data})
});
}
render()
{
const {emps} = this.state;
return(
<Table className="mt-4" striped bordered hover size="sm">
<thead>
<tr>
<th>Id</th>
<th>FirstName</th>
<th>LastName</th>
<th>Email</th>
<th>Address</th>
</tr>
</thead>
<tbody>
{emps.map(emps =>
<tr key ={emps.Id}>
<td>{emps.Id}</td>
<td>{emps.FirstName}</td>
</tr>
)}
</tbody>
</Table>
)
}
}
export default EmployeeList;
please suggest me how to solve this in this code.
thanks
Looks like you don't have Id in emps data.
Instead you can pass index.
<tbody>
{emps.map((emps,index) =>
<tr key ={index}>
<td>{emps.Id}</td>
<td>{emps.FirstName}</td>
</tr>
)}
</tbody>

React-Redux - rank counter table

I am currently working on one of FCC's project, specifically to this one:
https://www.freecodecamp.com/challenges/build-a-camper-leaderboard
I was able to get it working just fine--I am able to click either recent or all-time scores and it will re-render the page accordingly.
The only thing I am missing is rendering the rank number appropriately. As of now, it is just current stack of number 1.
Here's my current code:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { recentData } from '../actions/index'
import { allTimeData } from '../actions/index'
export default class TableBoard extends Component {
constructor(props){
super(props);
}
componentDidMount() {
this.props.recentData() //fetch data most recent top
}
renderData(userData){
const name = userData.username;
const recent = userData.recent;
const allTime = userData.alltime;
let rank = 1;
return(
<tr key={name}>
<td>{rank}</td>
<td>{name}</td>
<td>{recent}</td>
<td>{allTime}</td>
</tr>
)
}
getRecentData(){
console.log('recent data')
this.props.recentData()
}
getAllTimeData(){
console.log('all-time data')
this.props.allTimeData();
}
render(){
return(
<table className="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Camper Name</th>
<th
onClick={this.getRecentData.bind(this)}
>Points in 30 days
</th>
<th
onClick={this.getAllTimeData.bind(this)}
>All-time Posts
</th>
</tr>
</thead>
<tbody>
{this.props.FCCData.map(this.renderData)}
</tbody>
</table>
)
}
}
function mapStateToProps(state){
return {
FCCData: state.collectData
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({ recentData, allTimeData }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(TableBoard);
How can I add extra information into renderData function to display the rank correctly? I am assuming I need to an counter?
Pass index into map
renderData(item,index){
const name = item.username;
const recent = item.recent;
const allTime = item.alltime;
return(
<tr key={name}>
<td>{index+1}</td>
<td>{name}</td>
<td>{recent}</td>
<td>{allTime}</td>
</tr>
)
}
Table Body
<tbody>
{this.props.FCCData.map(this.renderData}
</tbody>

Resources