ReactJs function call and instead saw an expression no-unused-expressions - javascript

I'm trying to prepare a restfulpi at reactjs. But because I'm new to reactjs and I'm not very fluent in English, I have encountered a problem. the purpose of my application is to list the books of a publisher. you can access my code and error from below. I can do it if you help me. Thank you.
Error:
Line 21: Expected an assignment or function call and instead saw an expression no-unused-expressions
My Codes:
`` `
class App extends Component {
state = {
books:[]
}
componentWillMount(){
axios.get('http://localhost:3000/books').then(( response)=>{
this.setState({
books: response.data
})
});
}``
`` `
render() {
let books = this.state.books.map((book) =>
{
return
(
<tr key={book.id}>
<td>{book.id}</td>
<td>{book.title}</td>
<td>{book.rating}</td>
<td>
<Button color="success" size="sm" className="mr-2">Edit </Button>
<Button color="danger" size="sm">Sil</Button>
</td>
</tr>
)
});``
`` `
return (
<div className="App container">
<h1>Book List</h1><br></br>
<Table>
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Rating</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{books}
</tbody>
</Table>
</div>
);``

Try this:
render() {
const books = this.state.books.map(book => {
return (
<tr key={book.id}>
<td>{book.id}</td>
<td>{book.title}</td>
<td>{book.rating}</td>
<td>
<Button color="success" size="sm" className="mr-2">
Edit{' '}
</Button>
<Button color="danger" size="sm">
Sil
</Button>
</td>
</tr>
);
});
return <tbody>{books}</tbody>;
}
According to this answer it is a common mistake in the render function.

You are missing the return statement in your render method.
render() {
....
...
return (
<tbody>
{books}
</tbody>
)
}

Related

Handling array length in React

I have an array of results I'm wanting to render in a table:
const ScanOutput = () => (
<div class="results">
<h1>
<b>Scan Results</b>
</h1>
<h3>{results.length} results returned</h3>
<table class="styled-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{results.map((result) => (
<tr>
<td>{result.id}</td>
<td>{result.name}</td>
</tr>
))}
</tbody>
</table>
</div>
);
This works, but I'd like to add some extra features - for example, if no results are returned (e.g. results.length == 0) I'd like to render "No results found" instead of an empty table. Furthermore, I'd also like to make it so that with this section here:
<h3>{results.length} results returned</h3>
If only 1 result is returned it renders this instead:
<h3>{results.length} result returned</h3>
What's the cleanest way to do this in React?
You can render conditionally.
<div class="results">
{result?.length > 0 ?
<>
<h1>
<b>Scan Results</b>
</h1>
<h3>{results.length} results returned</h3>
<table class="styled-table">
{...}
</table>
</>
:
<h1>No results found</h1>
}
</div>
You can create a new component for the results table
const ResultsTable = ({ results }) => {
if (results?.length === 0) return <h3>No results found</h3>;
if (results?.length === 1) return ...;
return (
<table class="styled-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{results.map((result) => (
<tr>
<td>{result.id}</td>
<td>{result.name}</td>
</tr>
))}
</tbody>
</table>
)
}

Switching between 2 table objects in React JS

I'm pretty new to react and I'm having trouble switching between these 2 tables. I looked at the documentation for inline conditional statements and this was all I got. I want it to switch between the tables after clicking the button.
const customer_table = (
<Table striped bordered hover>
<thead>
<tr>
<th>ID</th>
<th>Org Name</th>
<th>Status</th>
<th>More Info</th>
</tr>
</thead>
<tbody>
{customers.map(customer =>
<tr>
<td id="customer_id">{String(customer.customer_id).padStart(4, '0')}</td>
<td id="name">{customer.org_name}</td>
<td id="email">{customer.cus_status}</td>
<td><Link to={{
pathname: `/profile/${customer.customer_id}`,
query: { customer_id: `${customer.customer_id}`}
}} className="btn btn-primary">Profile</Link></td>
</tr>
)}
</tbody>
</Table>
)
return (
<td>
<div className="toggleCustomers">
<button onClick={toggleDeavtivated} >Show Deactivated Customers</button>
</div>
<ul>
{
show_deactivated ? `${deactivatedCustomer_table}`
: `${customer_table}`
}
</ul>
</td>
);
To do that you need to use state, you can read about this from this url
By using state you can update rendering by track any change from button, for example for your case:
const [firstTable, setFirstTable] = useState(true);
return (
<div>
<p>You clicked {firstTable}</p>
<button onClick={() => setFirstTable(!firstTable)}>
Click me
</button>
{ firstTable ? ${deactivatedCustomer_table}`
: `${customer_table}`
}
</div>
);

Error : 'list' is not defined no-undef 'route' is not defined no-undef

I am building web application using railway api, on submitting train number I am trying to display data but getting the above error. Actually I used if else condition on fetching data.
below is the code.
import React, { Component } from "react";
export default class TrainRoute extends Component {
constructor(props) {
super(props);
this.state = { trainNumber: "", trainRouteList: "" };
this.onChange = this.onChange.bind(this);
this.onSubmitForm = this.onSubmitForm.bind(this);
}
onChange(e) {
this.setState({ [e.target.id]: e.target.value } );
}
onSubmitForm(e) {
e.preventDefault();
fetch(
`https://api.railwayapi.com/v2/route/train/${
this.state.trainNumber
}/apikey/sch9lj34uy/`
)
.then(res => res.json())
.then(data => {
this.setState({ trainRouteList: data }, () =>
console.log(this.state.trainRouteList)
);
});
this.setState({ trainNumber: "" });
}
render() {
const { trainRouteList } = this.state;
if (!trainRouteList) {
const list = <div>No Trains Details to display</div>;
const route = <div>No Routes to display</div>;
} else {
const list = (
<div>
<table>
<tbody>
<tr>
<td>Train Name :</td>
<td> {trainRouteList.train.name} </td>
</tr>
<tr>
<td>Train Number :</td>
<td> {trainRouteList.train.number} </td>
</tr>
<tr>
<td>Class :</td>
<td>
{trainRouteList.train.classes.map(trainClass => (
<span key={trainClass.code}>{trainClass.code},</span>
))}{" "}
</td>
</tr>
</tbody>
</table>
</div>
);
const route = trainRouteList.route.map(routeInfo => (
<table>
<tbody>
<tr>
<td>Station :</td>
<td> {routeInfo.station.name} </td>
</tr>
<tr>
<td>Departure Time :</td>
<td> {routeInfo.schdep} </td>
</tr>
<tr>
<td>Arrival Time :</td>
<td> {routeInfo.scharr} </td>
</tr>
</tbody>
</table>
));
}
return (
<div>
<div className="container">
<form
onSubmit={this.onSubmitForm}
className="col-md-8 col-md-offset-4"
>
<div className="row">
<div className="col-md-3">
<input
type="number"
className="form-control input-lg"
placeholder="Train Number"
id="trainNumber"
value={this.state.trainNumber}
onChange={this.onChange}
/>
</div>
<div className="col-md-1">
<button type="submit" className="btn btn-warning btn-lg">
Check Route
</button>
</div>
</div>
</form>
</div>
<div className="card card-fluid">
<div className="container">
{list}
<h3>Train Route</h3>
{route}
</div>
</div>
</div>
);
}
}
Getting error at list and route in render method. Can Anyone tell
me why I am getting this error as I tried all possible solution
Its because list and route are block level variable and you are trying to access them outside of block.
Solution is, Define those variables outside then update the value in if and else block, by that way we can access anywhere inside render method. Like this:
render() {
const { trainRouteList } = this.state;
let list, route;
if (!trainRouteList) {
list = <div>No Trains Details to display</div>;
route = <div>No Routes to display</div>;
} else {
list = ....;
route = ....;
}

Conditional rendering in ReactJS between button and normal text

I have one object array say defect and now if the status of the defect is open then it should show as button and it should read close the defect and if it is closed, then instead as button it should just mention as closed.
So, here statusRender is the issue and is now working as expected in the last column. Cant figure out what I am missing. Any leads?
render() {
if (defect.defect_status == 'open') {
statusRender = <button key={index} data-id={defect.id} onClick={() => this.showAlert(defect.defect_id)}>{defect.defect_status}</button>;
} else {
statusRender = { defect.defect_status };
}
return (
<div>
<table className="table table-bordered table-hover">
<thead>
<tr>
<th>Defect ID</th>
<th>Category</th>
<th>Description</th>
<th>Priority</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{this.state.defectList.map((defect, index) => {
return (
<tr key={index}>
<td> {defect.defect_id} </td>
<td>{defect.defect_category}</td>
<td>{defect.defect_description}</td>
<td>{defect.defect_priority}</td>
<td> {statusRender}
</td>
</tr>
);
})
}
</tbody>
</table>
</div>
)
}
it is a scope issue you cannot declare defect outside of the map function
{this.state.defectList.map((defect,index) => {
return (
<tr key={index}>
<td> {defect.defect_id} </td>
<td>{defect.defect_category}</td>
<td>{ defect.defect_description}</td>
<td>{ defect.defect_priority}</td>
<td>
{
defect.defect_status === 'open'
? <button key={index} data-id={defect.id} onClick = {() => this.showAlert(defect.defect_id)}>{defect.defect_status}</button>;
: defect.defect_status;
}
</td>
</tr>
);
})
}
Thanks to user1095118 removing the semi colons did the job. I was missing the correctness of the curly braces which solved the issue
{
defect.defect_status == 'open'
?<button key={index} data-id={defect.id} onClick = {() => this.showAlert(defect.defect_id)}>{defect.defect_status}</button> : defect.defect_status
}
If you just need to access status string instead of the button maybe you should remove brackets in your if else statement
render() {
if(defect.defect_status=='open') {
statusRender = <button key={index} data-id={defect.id} onClick = {() => this.showAlert(defect.defect_id)}>{defect.defect_status}</button>;
} else {
// No brackets here ?
statusRender = defect.defect_status;
}
return (
<div>
<table className="table table-bordered table-hover">
<thead>
<tr>
<th>Defect ID</th>
<th>Category</th>
<th>Description</th>
<th>Priority</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{this.state.defectList.map((defect,index) =>{
return(
<tr key={index}>
<td> {defect.defect_id} </td>
<td>{defect.defect_category}</td>
<td>{ defect.defect_description}</td>
<td>{ defect.defect_priority}</td>
<td> {statusRender}
</td>
</tr>
);
})
}
</tbody>
</table>
</div>
)
}
}

Communicating beteween parent and child with row ReactJs

I try to call a parent function from a child function.
I follow this example :Expose Component Functions but with this code my page does not load and my console is empty so i do not know find the problem.
I use webpack with babel and webpack-dev-server
Thank you for your answers.
I am sorry for my english.
class Row extends React.Component {
render(){
return(
<tr className="animated slideInRight">
<th scope="row">{this.props.data.ville_id}</th>
<td>{this.props.data.ville_nom}</td>
<td>{this.props.data.ville_nom_reel}</td>
<td>{this.props.data.ville_canton}</td>
<td><button className="btn btn-success" onClick={this.props.onClick} >Full Detail</button></td>
</tr>
)
}
}
export default class Metier extends React.Component {
constructor() {
super();
this.state = {
data: [],
};
}
deleteClick(e){
console.log("ici")
}
render(){
return(
<table className="table table-striped">
<thead>
<tr>
<th>IdVille</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.state.data.map(function(result,i){
var boundClick = this.deleteClick.bind(this,i)
return(
<Row onClick={boundClick} key={i} data={result} />
)
})}
</tbody>
</table>
)
}
}
You have to use the arrow function in the map so you can access this:
{this.state.data.map((result,i) => {
var boundClick = this.deleteClick.bind(this,i)
return(
<Row onClick={boundClick} key={i} data={result} />
)
})}
By using a simple function you create a new context and in that function you cannot access this.deleteClick. Using an arrow function you can still access it.

Categories