ES6 React JS methods Calendar Component - javascript

I am creating a calendar component and at the moment can't work out why react won't render to the DOM the returned elements of my renderWeekDays method?
Currently I have the following:
export default class CalendarApp extends React.Component {
constructor() {
super();
// Bind Methods
this.renderWeekDays = this.renderWeekDays.bind(this);
}
renderWeekDays() {
return (
<tr><td>Render Week days Please</td></tr>
)
}
render() {
let overviewContent,
checkRates
// Add Check rates and availability section if Rooms page
if (this.props.roomPage) {
checkRates = (
<div>
<h2>Check rates and availability</h2>
<small>or call us on 0330 100 3180</small>
</div>
)
}
// Determine whether to show placeholder or actual dates
if (this.props.dateSelected) {
overviewContent = (
<div>
<span className="icon">Icon</span>
<span className="date-from">21 Jun</span>
<span className="seperate">-></span>
<span className="date-to">25 Jun</span>
<span className="clear">X</span>
</div>
)
} else {
overviewContent = (
<div>
<span className="icon">Icon</span>
<span className="check-in">Check-in</span>
<span className="seperate">-></span>
<span className="check-out">Check-out</span>
</div>
)
}
return (
<div className="calendar hotelroom-follow-calendar">
{ checkRates }
<div className="calendar-overview">
<button>
{ overviewContent }
</button>
</div>
<div className="calendar-container">
<div className="calendar-month">
<span className="previous">Prev</span>
June
<span className="next">Next</span>
</div>
<table className="calendar-table">
<thead>
<tr>
<td>M</td>
<td>T</td>
<td>W</td>
<td>T</td>
<td>F</td>
<td>S</td>
<td>S</td>
</tr>
</thead>
<tbody>
{ this.renderWeekDays }
</tbody>
</table>
</div>
{ Moment().format() }
</div>
)
}
I am not being presented with any errors, it simply won't load in <tr><td>Render Week days Please</td></tr>.
Any help would be much appreciated as I have double checked all bind() methods etc.

You need to actually invoke the function in your jsx.
<tbody>
{ this.renderWeekDays }
</tbody>
needs to be
<tbody>
{ this.renderWeekDays() }
</tbody>
and voila, it should work!

Related

Why cant i use a function to fill a table in REACTJS

I wrote a function in REACTJS that helps me to read a JSON-File and to display the content of the JSON-File. When I use the code of the function inside of a body the display of the content works fine. But now i want to use the function to fill a table with the content of the JSON and it wont work - the page stays empty. Thank you in advance!
The Function:
function FillData() {
<div className="App">
{
Data.map( datan => {
return(
<div className="box">
{datan.personalActivationWord}
</div>
)
} )
}
</div>
}
Trying to use it to fill a table (Tabledata for Setting1):
function Table() {
return (
<div className={navto.table}>
<div className={navto.header}>HMI</div>
<FillData />
<table className>
<tr>
<th>Setting</th>
<th>Wert</th>
<th>Status</th>
</tr>
<tr>
<td>Setting1</td>
<td><FillData /></td>
<td>Aktualisiert vor 3 Sek.</td>
</tr>
<tr>
<td>Setting2</td>
<td>AKTIV</td>
<td>Aktualisiert vor 3 Sek.</td>
</tr>
<tr>
<td>Setting3</td>
<td>AKTIV</td>
<td>Aktualisiert vor 3 Sek.</td>
</tr>
</table>
</div>
)
}
You are not returning anything in your FillData function.
function FillData() {
return <div className="App">
{
Data.map( datan => {
return(
<div className="box">
{datan.personalActivationWord}
</div>
)
} )
}
</div>
}

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

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>
)
}

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 = ....;
}

How to sort API response for some field

I just start to learn Reactjs and have stopped with some question.
I've fetched data through axios for some API endpoint(get countries with some data like population,currencies,region etc.) and I want to sort data for some field(region or population for example).
I thought that in reactjs it will be simple to do and reactjs have some built-in things to do that. But when I've tried to do that and when I've searched answer in google I was really exposed. What is the best way to implement sorting? How can I do that?
What I've tried:
import React, { Component } from 'react';
import axios from 'axios';
import './App.css';
class App extends Component {
constructor(props){
super(props)
this.state={
countries:[],
}
}
componentDidMount(){
axios.get('https://restcountries.eu/rest/v2/all')
.then(response => {
this.setState({
countries:response.data
})
})
.catch((error) => {
console.log("error", error)
})
}
render(){
return(
<div className = 'table'>
<table>
<tbody>
<tr>
<th>Country name </th>
<th>Currencies</th>
<th>Region </th>
<th>Flag </th>
<th >Population</th>
<th>Languages</th>
</tr>
{
this.state.countries.map((country,id) => {
return(
<tr className="tableRow">
<td> {country.name}</td>
<td>{country.currencies.map((currency,i)=>{
return (
<p>
<span>{currency.name} </span>
<span>{currency.symbol} </span>
</p>
)
})} </td>
<td> {country.region}</td>
<td> <img src={country.flag} alt={country.denonym}/> </td>
<td> {country.population} </td>
<td> {country.languages.map((language)=>{
return (
<span> {language.name} </span>
)
})} </td>
</tr>
)
})
}
</tbody>
</table>
</div>
)
}
}
export default App;
Basically what you need to do is something like this:
...
this.state.countries.sort(/* Provide sort function here */).map((country,id) => {
...
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

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