React Fuse Component error for default export - javascript

I have this code to add div to table onclick, but I have added it from Stack to a Fuse project which has its own template. Please have a look at this code, I think there is a very simple problem with it. I am new to React, and I don't understand, how can I export the class. Whatever I tried, there is an error on it. Here is the code:
const useStyles = makeStyles({
layoutRoot: {},
});
Class Mdf extends React.Component ({
getInitialState: function () {
return {
tablerows: [
{ fname: "Tom", lname: "Moody", age: 23 }
]
};
},
addRow: function () {
// add new data from here
var newdata = { fname: "Tom", lname: "Moody", age: 23 }
//take the existing state and concat the new data and set the state again
this.setState({ tablerows: this.state.tablerows.concat(newdata) });
},
rows: function () {
return this.state.tablerows.map(function (row, i) {
return (<tr key={i}>
<td>{row.fname}</td>
<td>{row.lname}</td>
<td>{row.age}</td>
</tr>);
});
},
render: function () {
const classes = useStyles();
return (
<FusePageSimple
classes={{
root: classes.layoutRoot,
}}
header={
<div className="p-24">
<h1>Site Details</h1>
</div>
}
contentToolbar={
<div className="px-24">
<h4>Content Toolbar22222</h4>
</div>
}
content={
<div className="p-24">
<div>
<table>
<tr>
<td> row 1 </td>
</tr>
<tr>
<td> row 2 </td>
</tr>
<tr>
<td> row 3 </td>
</tr>
{this.rows()}
</table>
<button id="addBtn" onClick={this.addRow}>ADD</button>
</div>
</div>
}
/>
);
}
});
// React.render(<Mdf />)
export default Mdf
And the error message which shows up is this:
Attempted import error: './Mdf' does not contain a default export (imported as 'Mdf').

Related

How to show the specified table row data based on the filter option in react js

I am new to reactjs. I am showing the json data in the table. I also want to display only specific table row data for the specific filter option.
Here I want when noida is selected then the table should display only 2 nd 3rd row of the table.
when Moradabad is selected the it should display only first row of the table.
Here I am attaching the image which displays all the rows , please help me in this filtration logic show only on selected city.
The code is below
import React from 'react';
import './style.css';
export default class JsonDataDisplay extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{
id: 1,
name: 'Akshit',
city: 'Moradabad',
},
{
id: 2,
name: 'Nikita',
city: 'Noida',
},
{
id: 3,
name: 'Deeksha',
city: 'Noida',
}
],
};
}
render() {
const displaydata = this.state.data.map((info) => (
<tr>
<td>{info.id}</td>
<td>{info.name}</td>
<td>{info.city}</td>
</tr>
));
return (
<>
<FilterComponent />
<br />
<section>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>city</th>
</tr>
</thead>
<tbody>{displaydata}</tbody>
</table>
</section>
</>
);
}
}
function FilterComponent(props) {
const data = ['All', 'Noida', 'Moradabad'];
return (
<div>
<div>city</div>
<select>
{data.map((field) => (
<option>{field}</option>
))}
</select>
</div>
);
}
Few more things to do,
Define another state variable to keep the selectedCity state
this.state = {
data: [
...
...
],
selectedCity: "All"
};
Define a onChange handler function to set the selected city
setSelectedCity = (selectedCity) => {
this.setState({ selectedCity });
};
Add a filter for displaydata as below
const displaydata = this.state.data
.filter(
({ city }) =>
this.state.selectedCity === "All" || this.state.selectedCity === city
)
.map((info) => (
<tr>
<td>{info.id}</td>
<td>{info.name}</td>
<td>{info.city}</td>
</tr>
));
Pass setSelectedCity as a prop to FilterComponent
<FilterComponent setSelectedCity={this.setSelectedCity} />
Update the FilterComponent to set the selectedCity when selection changes.
function FilterComponent({ setSelectedCity }) {
const data = ["All", "Noida", "Moradabad"];
return (
<div>
<div>city</div>
<select onChange={(e) => setSelectedCity(e.target.value)}>
{data.map((field) => (
<option value={field}>{field}</option>
))}
</select>
</div>
);
}
Code Sandbox

How to change data from the parent component on Vue

I started using Vue today and I'm doing a Todo app.
How can I change the APIData array from the ItemRow child component
<template>
<div id="index">
<div class="container">
<div class="card">
<div class="card-header">
<div class="card-header-title">
TO-DO
</div>
<div class="card-header-input">
<input type="text" v-model="newTask">
<button #click="createTask(newTask)">Create</button>
</div>
</div>
<div class="card-content">
<table>
<thead>
<th>Title</th>
<th>Created At</th>
<th>Completed</th>
<th>Delete</th>
</thead>
<tbody>
<ItemRow
v-for="(task, index) in APIData"
:key="task.id"
:task="task"
:index="index"
>
</ItemRow>
</tbody>
</table>
</div>
</div>
</div>
</div>
</template>
<script>
import { api } from '../axios-api'
import ItemRow from '../components/ItemRow.vue'
export default {
name: 'index',
components: {
ItemRow,
},
data() {
return {
newTask: '',
APIData: [],
}
},
created() {
api.get('tasks/',)
.then(response => {this.APIData = response.data})
},
methods: {
createTask(title) {
api.post('tasks/', {title: title})
.then((response) => {
this.APIData.unshift(response.data)
this.newTask = ''
})
},
},
}
</script>
ItemRow component:
<template>
<tr>
<td>{{ task.title }}</td>
<td>{{ formatDate(task.created_at) }}</td>
<td><input type="checkbox" :checked="task.complete" #click="completeTask(task)"></td>
<td><button #click="deleteTask(task, index)">Delete</button></td>
</tr>
</template>
<script>
import moment from 'moment';
import { api } from '../axios-api'
import APIData from '../views/Index.vue'
export default {
name: "ItemRow",
props: {
task: {
type: Object,
required: true,
},
index: {
type: Number,
required: true,
}
},
methods: {
completeTask(task) {
api.patch(`tasks/${task.id}/`, { complete: !task.complete })
.catch(response => {
console.log('error', response)
})
},
deleteTask(task, index) {
api.delete(`tasks/${task.id}/`)
.then(() => {
APIData.splice(index, 1)
})
},
formatDate(date) {
return moment(date).format('YYYY-MM-DD');
},
}
}
</script>
When I click on delete vue is calling #click="deleteTask(task, index)", How I update my APIData about this change? I', trying to import import APIData from '../views/Index.vue' but I'm not confident on this method.
you cant do like this import APIData from '../views/Index.vue' for child to parent communication we want to use $emit in vuejs && for parent to child we want to use props

React: How to update the state of an object when a user selects a value from a drop-down menu?

I'm new to coding and I'm trying to create a project which has one component where a user can select if a student is Present, Absent, or Late for a class. I'm using React for this and I have created the display with a drop-down menu that shows the options for Present, Absent, or Late.
I'm having trouble changing the student's attendance value after the user has selected if they are present or not from the drop-down menu. Ideally, I would like the submitted results to be displayed in another tab with a list of all the students and their attendance for that day. This is part of the code that I have:
Attendance Component:
class Attendance extends Component {
constructor(props) {
super(props);
this.state = {
students: StudentsAlphabetical,
list: [
{idA: "0", option: "Present"},
{idA: "1", option: "Absent"},
{idA: "2", option: "Late"},
],
studentAttendance: {
id: students.id,
FirstName: students.firstName,
LastName: students.lastName,
Attendance: " ",
},
};
// Destructuring this.state.students
const { id, lastName, firstName } = this.state.students;
// Getting the length of the students array
const studentsLength = this.state.students.length;
// Destructuring this.state.list
const { idA, option } = this.state.list;
};
changeAttendance method:
changeAttendance() {
this.state.studentAttendance.map(value => (
<tr key={value.id}>
<td>{value.firstName}</td>
<td>{value.lastName}</td>
<td>{value.Attendance}</td>
</tr>)
};
render method:
render() {
return(
<form onSubmit={this.handleSubmit}>
<Table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
{/*Use the map array method to go through the students array and create the table row for each student*/}
{this.state.students.map((student =>
<tr key={student.id}>
<td>{student.firstName}</td>
<td>{student.lastName}</td>
<td> {/*Creating dropdown button that will show if student is Present, Absent or Late*/}
<select>
{this.state.list.map(item => (
<option key={item.idA} value={item.option}>
{item.option}
</option>
))}
</select>
</td>
</tr>))}
</tbody>
</Table>
<Button color="secondary" size="lg" block onClick={this.changeAttendance}> {/*Submit button*/}
Submit Attendance
</Button>
</form>
);
};
I would like some advice as to how I can change the Attendance part in the studentAttendance array after the user has selected from the drop-down menu if the student was either Present, Absent or Late. Thank you!
I think your target is something like this, try this way:
sandbox link:
https://codesandbox.io/s/fervent-hoover-9w31y?file=/src/App.js
import "./styles.css";
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
selectValue: "Absent",
students: [
{ id: 1, name: "st1", attendance: "-" },
{ id: 2, name: "st1", attendance: "-" },
{ id: 3, name: "st1", attendance: "-" }
]
};
}
handleChange = (e, id) => {
let newStudents = this.state.students.map((item) => {
if (item.id === id) {
return { ...item, attendance: e.target.value };
} else {
return item;
}
});
this.setState({ students: newStudents });
};
render() {
return (
<div>
<table style={{ marginTop: 20 }}>
<p>List: </p>
{this.state.students.map((item) => {
return (
<tr>
<td>id: {item.id}</td>
<td>name: {item.name}</td>
<td>
attendance:{" "}
<span>
<select
value={item.attendance}
onChange={(e) => this.handleChange(e, item.id)}
>
<option value="Present">Present</option>
<option value="Absent">Absent</option>
<option value="Late">Late</option>
</select>
</span>
</td>
</tr>
);
})}
</table>
</div>
);
}
}
export default App;

how can i add new row my react bootstrap table

I created the table I mentioned below using React js. When I click on the button below the table, I want to add a new row to the table. I have listed the react code I wrote below. how can I do that?
My React Code
const PPP13 = (props) => {
return (
<Jumbotron>
<p className="btn-group">13- List all owners of 20% or more of the equity of the Applicant</p>
<Table striped bordered hover>
<thead>
<tr>
<th>Owner Name</th>
<th>Title</th>
<th>Ownership %</th>
<th>TIN (EIN, SSN)</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<FormControl aria-label="DDD"/>
</td>
<td>
<FormControl aria-label="DDD"/>
</td>
<td>
<FormControl aria-label="DDD"/>
</td>
<td>
<FormControl aria-label="DDD"/>
</td>
<td>
<FormControl aria-label="DDD"/>
</td>
</tr>
</tbody>
</Table>
<Button className="btn-group" name="add" value="No">
Add more owners
</Button>
</Jumbotron>
)
}
Here is what you can do. Lets say you have a Main component which will get all details.
class Products extends React.Component {
constructor(props) {
super(props);
// this.state.products = [];
this.state = {};
this.state.filterText = "";
this.state.products = [
{
id: 1,
category: 'Sporting Goods',
price: '49.99',
qty: 12,
name: 'football'
}, {
id: 2,
category: 'Sporting Goods',
price: '9.99',
qty: 15,
name: 'baseball'
}, {
id: 3,
category: 'Sporting Goods',
price: '29.99',
qty: 14,
name: 'basketball'
}, {
id: 4,
category: 'Electronics',
price: '99.99',
qty: 34,
name: 'iPod Touch'
}, {
id: 5,
category: 'Electronics',
price: '399.99',
qty: 12,
name: 'iPhone 5'
}, {
id: 6,
category: 'Electronics',
price: '199.99',
qty: 23,
name: 'nexus 7'
}
];
}
handleAddEvent(evt) {
var id = (+ new Date() + Math.floor(Math.random() * 999999)).toString(36);
var product = {
id: id,
name: "empty row",
price: "mpty row",
category: "mpty row",
qty: 0
}
this.state.products.push(product);
this.setState(this.state.products);
}
handleProductTable(evt) {
var item = {
id: evt.target.id,
name: evt.target.name,
value: evt.target.value
};
var products = this.state.products.slice();
var newProducts = products.map(function(product) {
for (var key in product) {
if (key == item.name && product.id == item.id) {
product[key] = item.value;
}
}
return product;
});
this.setState({products:newProducts});
};
render() {
return (
<div>
<ProductTable onProductTableUpdate={this.handleProductTable.bind(this)} onRowAdd={this.handleAddEvent.bind(this)} products={this.state.products} />
</div>
);
}
}
This contains the code for adding row.Then for the table do something like this.
class ProductTable extends React.Component {
render() {
var onProductTableUpdate = this.props.onProductTableUpdate;
var product = this.props.products.map(function(product) {
return (<ProductRow onProductTableUpdate={onProductTableUpdate} product={product} key={product.id}/>)
});
return (
<div>
<button type="button" onClick={this.props.onRowAdd} className="btn btn-success pull-right">Add</button>
<table className="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>price</th>
<th>quantity</th>
<th>category</th>
</tr>
</thead>
<tbody>
{product}
</tbody>
</table>
</div>
);
}
}
Now for the row Comoponent:
class ProductRow extends React.Component {
render() {
return (
<tr className="eachRow">
<td>
{this.props.product.id}
</td>
<td>
{this.props.product.price}
</td>
<td>
{this.props.product.qty}
</td>
<td>
{this.props.product.category}
</td>
</tr>
);
}
}
Working Example:
https://jsfiddle.net/mrAhmedkhan/nvgozjhy/
Ok here's my plan:
First we create a state to hold all the data for the table. I've used an object instead of an array as it's much easier to do the change handling. With arrays you always end up doing all this awkward splicing. You can always parse the object out into an array when you're ready to use it elsewhere.
Then we render out each row of the table by mapping over the entries in our table state. Note we also write the change handler inside the map, meaning we can easily use the rowId (tableData key) to set our new state when a change comes in.
Finally we plop in a button to add more rows. This has a click handler associated with it (handleAddRowClick) which counts the number of rows we have and uses this to generate a new rowId. We use the new rowId to expand the tableData state to include a new defaultRow. I defined defaultRow outside of the function, this prevents it from being redeclared on every render.
import React, { useState } from 'react'
import { Table, Input, Button } from 'reactstrap'
const defautRow = { colA: '', colB: '' }
const IncreasableTable = props => {
const [tableData, setTableData] = useState({
row1: { colA: '', colB: '' }
})
const handleAddRowClick = () => {
const extantRowsCount = Object.keys(tableData).length
setTableData(s => ({
...s,
[`row${extantRowsCount}`]: defautRow
}))
}
return (
<>
<Table>
{
Object.entries(tableData).map(([rowId, data]) => {
const handleChange = ({ target: { name, value } }) => {
setTableData(s => ({
...s,
[rowId]: {
...s[rowId],
[name]: value
}
}))
}
return (
<tr key={rowId}>
<td>
<Input name="colA" value={data.colA} onChange={handleChange}/>
<Input name="colB" value={data.colB} onChange={handleChange}/>
</td>
</tr>
)
})
}
</Table>
<Button onClick={handleAddRowClick}>Click me to add more rows</Button>
</>
)
}
export default IncreasableTable

How to only delete one item at a time in ReactJS?

I'd like to, when a user deletes on row, for only that row to be deleted. Currently that only happens sometimes. And when you have only two items left to delete, when you click on the delete button, the row's data toggles and replaces itself. It doesn't actually delete.
mainCrud.js - houses the add and delete
crudAdd.js - defines state, event handlers, renders the form itself
crudTable.js - maps pre-defined rows defined in mainCrud.js, renders the table itself
Link to CodeSandbox (tables are under campaigns, dev and news tabs).
Any idea what could be causing this?
MainCrud.js
import React, { useState } from "react";
import CrudIntro from "../crud/crudIntro/crudIntro";
import CrudAdd from "../crud/crudAdd/crudAdd";
import CrudTable from "../crud/crudTable/crudTable";
const MainCrud = props => {
// Project Data
const projectData = [
{
id: 1,
name: "Skid Steer Loaders",
description:
"To advertise the skid steer loaders at 0% financing for 60 months.",
date: "February 1, 2022"
},
{
id: 2,
name: "Work Gloves",
description: "To advertise the work gloves at $15.",
date: "February 15, 2022"
},
{
id: 3,
name: "Telehandlers",
description: "To advertise telehandlers at 0% financing for 24 months.",
date: "March 15, 2022"
}
];
const [projects, setProject] = useState(projectData);
// Add Project
const addProject = project => {
project.id = projectData.length + 1;
setProject([...projects, project]);
};
// Delete Project
const deleteProject = id => {
setProject(projectData.filter(project => project.id !== id));
};
return (
<div>
<section id="add">
<CrudIntro title={props.title} subTitle={props.subTitle} />
<CrudAdd addProject={addProject} />
</section>
<section id="main">
<CrudTable projectData={projects} deleteProject={deleteProject} />
</section>
</div>
);
};
export default MainCrud;
CrudAdd.js
import React, { Component } from "react";
import "../crudAdd/crud-add.scss";
import "../../button.scss";
class CrudAdd extends Component {
state = {
id: null,
name: "",
description: "",
date: ""
};
handleInputChange = e => {
let input = e.target;
let name = e.target.name;
let value = input.value;
this.setState({
[name]: value
});
};
handleFormSubmit = e => {
e.preventDefault();
this.props.addProject({
id: this.state.id,
name: this.state.name,
description: this.state.description,
date: this.state.date
});
this.setState({
// Clear values
name: "",
description: "",
date: ""
});
};
render() {
return (
<div>
<form onSubmit={this.handleFormSubmit}>
<input
name="name"
type="name"
placeholder="Name..."
id="name"
value={this.state.name}
onChange={e => this.setState({ name: e.target.value })}
required
/>
<input
name="description"
type="description"
placeholder="Description..."
id="description"
value={this.state.description}
onChange={e => this.setState({ description: e.target.value })}
required
/>
<input
name="date"
type="name"
placeholder="Date..."
id="date"
value={this.state.date}
onChange={e => this.setState({ date: e.target.value })}
required
/>
<button type="submit" className="btn btn-primary">
Add Project
</button>
</form>
</div>
);
}
}
export default CrudAdd;
CrudTable.js
import React, { Component } from "react";
import "../crudTable/crud-table.scss";
class CrudTable extends Component {
render() {
const props = this.props;
return (
<div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Project Name</th>
<th scope="col">Project Description</th>
<th scope="col">Date</th>
<th scope="col"> </th>
</tr>
</thead>
<tbody>
{props.projectData.length > 0 ? (
props.projectData.map(project => (
<tr key={project.id}>
<td>{project.name}</td>
<td>{project.description}</td>
<td>{project.date}</td>
<td>
<button className="btn btn-warning">Edit</button>
<button
onClick={() => props.deleteProject(project.id)}
className="btn btn-danger"
>
Delete
</button>
</td>
</tr>
))
) : (
<tr>
<td>No projects found. Please add a project.</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
}
}
export default CrudTable;
This is because you are filtering over projectData. Update your deleteProject method to filter over your React.useState projects variable and it will work.
const deleteProject = id => {
setProject(projects.filter(project => project.id !== id));
};
See code sandbox example here.

Categories