Why is this child object empty, whatever i do? - javascript

I'm scratching my head bleeding on this one.
Tried:
Reservation.insert(this.state);
const res = // Setting every field manually
const res = // Setting every field manually aswell as setting the parkingLot fields, as you can see in the code
I have not idea what else I could try, res.parkingLot always stays as an empty object. Which results in errors when trying to insert.
The full function is here:
handleSubmit(event, $) {
event.preventDefault();
const res = {
date: new Date(),
parkingLot: {
_id: this.state.parkingLot._id,
number: this.state.parkingLot.number,
name: this.state.parkingLot.name,
description: this.state.parkingLot.description,
price: this.state.parkingLot.price,
reserved: this.state.parkingLot.reserved,
},
user: $.state.user,
begin: $.state.begin,
end: $.state.end,
};
console.log('Submit', res, this.state);
Reservation.insert(res);
}
I was asked to add my whole Code so:
ReservationForm.js
import React, {Component} from 'react';
import {Reservation} from "../../../shared/collections/Reservation";
import {withTracker} from "meteor/react-meteor-data";
import {ParkingLot} from "../../../shared/collections/ParkingLot";
import MaterialSelect from "../form/MaterialSelect";
import * as M from "materialize-css";
class ReservationForm extends Component {
constructor(props) {
super(props);
this.state = {};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleBeginPicker = this.handleBeginPicker.bind(this);
this.handleEndPicker = this.handleEndPicker.bind(this);
}
componentDidMount() {
let beginPicker = document.querySelector('#begin');
let endPicker = document.querySelector('#end');
M.Datepicker.init(beginPicker, {
autoClose: true,
onSelect: this.handleBeginPicker
});
M.Datepicker.init(endPicker, {
autoClose: true,
onSelect: this.handleEndPicker
});
}
handleBeginPicker(date) {
const event = {
target: {
name: 'begin',
value: date
}
};
this.handleInputChange(event);
}
handleEndPicker(date) {
const event = {
target: {
name: 'end',
value: date
}
};
this.handleInputChange(event);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(event) {
event.preventDefault();
try {
Reservation.insert(this.state, function(error) { error ? console.log( 'Insert Error', error) : null});
} catch (e) {
console.error(e);
M.toast({
html: e.reason,
});
}
}
render() {
const $ = this;
return (
<div className="row">
<h5>Reservierung anlegen</h5>
<form className="col s6" onSubmit={this.handleSubmit}>
<div className="row">
<label htmlFor='parkingLot'>Parkplatz</label>
<MaterialSelect ided='parkingLot'
named='parkingLot'
labeled='Parkplatz'
textField='name'
valueField='_id'
options={this.props.lots}
placeholder='Parkplatz wählen'
onChange={this.handleInputChange}/>
</div>
<div className="row input-field">
<input id='begin' name='begin' type='text' className='datepicker'
data-value={this.state.begin}/>
<label className='' htmlFor='begin'>Anfang</label>
</div>
<div className="row input-field">
<input id='end' name='end' type='text' className='datepicker'
data-value={this.state.end}/>
<label className='' htmlFor='end'>Ende</label>
</div>
<button className="btn waves-effect waves-light" type="submit" name="action"><i
className="material-icons right">create</i>Anlegen
</button>
</form>
</div>
);
}
}
export default withTracker(() => {
Meteor.subscribe('parkingLots');
return {
lots: ParkingLot.find({}).fetch(),
};
})(ReservationForm);
MaterialSelect.js
import React, {Component} from "react";
import {Random} from "meteor/random";
import * as M from "materialize-css";
export default class MaterialSelect extends Component {
constructor(props) {
super(props);
this.state = {value: this.props.value};
}
componentDidMount() {
let select = document.querySelector(`#${this.props.ided}`);
//M.FormSelect.init(select, {});
}
handleInputChange(event, $) {
event.preventDefault();
$.props.onChange(event);
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
const options = this.props.options.map(option => {
return <option value={!!this.props.valueField ? option[this.props.valueField] : option}
key={Random.id(4)}>{!!this.props.textField ? option[this.props.textField] : option}</option>
});
const $ = this;
return (
<select id={this.props.ided}
name={this.props.named}
defaultValue=''
value={this.state.value}
className='no-autoinit browser-default'
onChange={function(event) {$.handleInputChange(event, $)}} >
<option value="" disabled>{this.props.placeholder}</option>
<option value="crap value">Not Existing Value Test</option>
{options}
</select>
);
}
}

I tried this:
<script>
const res = {
date: new Date(),
parkingLot: {
_id: 11,
number: 12,
name: 'jhon',
description: 'j',
price: 3232,
reserved: true,
},
user: 'j',
begin: 'j',
end: 'j',
};
console.log(res);
</script>
and it works perfectly.
Are you sure all the properties are actually there? try to debug it in the console.
Does "this.state.parkingLot._id" actually returns a number?

Did you bind this in the component constructor?
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(evt) {
...
}
}
As an alternative, you can use class properties and declare your event handlers as arrow functions instead. For that you would need the babel plugin #babel/plugin-proposal-class-properties
Also take a look at: https://reactjs.org/docs/faq-functions.html

Related

Cannot Read Properties Of Undefined Reading handleCategory

I'm trying to handle simple click action , I'm using class based components and I binded the method and used "this" as per documentation but an error occurs sayin cannot read properties of handleCategory , here's my code
import React from 'react';
import classes from '../css/Landing.module.css';
import mainClasses from '../../MainCss/MainClasses.module.css';
import { LOAD_CATEGORIES } from '../../graphql/queries';
export default class Landing extends React.Component {
constructor(props) {
super(props);
this.state = {
categories: [],
loading: true,
category: null,
};
this.handleCategory = this.handleCategory.bind(this);
}
async componentDidMount() {
const { client } = this.props;
const { data } = await client.query({ query: LOAD_CATEGORIES });
const { categories } = data;
this.setState((prevState) => ({ ...prevState, categories: categories, loading: false, category: categories[0]?.name }));
}
handleCategory(e) {
this.setState((prevState) => ({ ...prevState, category: e.target.value }));
}
renderCategory(category) {
return (
<option onClick={this.handleCategory} key={category.name} value={category.name}>
{category.name}
</option>
);
}
render() {
return (
<div className={`${classes.root} ${mainClasses.container} ${mainClasses.column}`}>
<div className={`${mainClasses.container} ${mainClasses.row}`}>
<label className={classes.categorylabel}>Choose Category</label>
{this.state.loading ? 'loading' : <select className={classes.categorymenu}>{this.state.categories.map(this.renderCategory)}</select>}
</div>
<div>{this.state.category}</div>
</div>
);
}
}
Convert the handleCategory method to an arrow function:
handleCategory = (e) => {
this.setState((prevState) => ({ ...prevState, category: e.target.value }));
}
By doing this you can remove the explicit bind from the constructor.
For more info read here.

Reset table using reset button

I'm new React developer(mainly with hooks but did not find good example with hooks), here i have antd table with search functionality, my question is when user writes something in search then user gets different result, how to cancel that search by clicking 'Reset' button ?
my code:
https://codesandbox.io/s/antd-table-filter-search-forked-mqhcn?file=/src/EventsSection/EventsSection.js
You can add an id to your input into TitleSearch.js:
<Search
id='IDYOUWANT'
placeholder="Enter Title"
onSearch={onSearch}
onChange={onChange}
style={{ width: 200 }}
/>
And add event into EventsSection.js
ResetInput = () => {
const input = document.getElementById('IDYOUWANT');
input.value = '';
this.handleSearch('');
}
....
<button
onClick={this.ResetInput}
>Reset</button>
Change IDYOUWANT with your id
run this code
Created a new function for reset value and trigger it from reset button.
function:
resetValue = () =>{
this.setState({
eventsData: eventsData
});
}
And trigger from button
<button onClick={this.resetValue}>Reset</button>
all code::
import React, { Component } from "react";
import styles from "./style.module.css";
import { EventsTable } from "../EventsTable";
import { StatusFilter } from "../StatusFilter";
import { TitleSearch } from "../TitleSearch";
const eventsData = [
{
key: 1,
title: "Bulletproof EP1",
fileType: "Atmos",
process: "match media",
performedBy: "Denise Etridge",
operationNote: "-",
updatedAt: "26/09/2018 17:21",
status: "complete"
},
{
key: 2,
title: "Dexter EP2",
fileType: "Video",
process: "Compliance",
performedBy: "Dane Gill",
operationNote: "passed",
updatedAt: "21/09/2018 12:21",
status: "inProgress"
}
];
class EventsSection extends Component {
constructor(props) {
super(props);
this.state = {
eventsData
};
}
handleFilter = (key) => {
const selected = parseInt(key);
if (selected === 3) {
return this.setState({
eventsData
});
}
const statusMap = {
1: "complete",
2: "inProgress"
};
const selectedStatus = statusMap[selected];
const filteredEvents = eventsData.filter(
({ status }) => status === selectedStatus
);
this.setState({
eventsData: filteredEvents
});
};
handleSearch = (searchText) => {
const filteredEvents = eventsData.filter(({ title }) => {
title = title.toLowerCase();
return title.includes(searchText);
});
this.setState({
eventsData: filteredEvents
});
};
handleChange = (e) => {
const searchText = e.target.value;
const filteredEvents = eventsData.filter(({ title }) => {
title = title.toLowerCase();
return title.includes(searchText);
});
this.setState({
eventsData: filteredEvents
});
};
resetValue = () =>{
this.setState({
eventsData: eventsData
});
}
render() {
return (
<section className={styles.container}>
<header className={styles.header}>
<h1 className={styles.title}>Events</h1>
<button onClick={this.resetValue}>Reset</button>
<TitleSearch
onSearch={this.handleSearch}
onChange={this.handleChange}
className={styles.action}
/>
</header>
<EventsTable eventsData={this.state.eventsData} />
</section>
);
}
}
export { EventsSection };
Here is what i did in order to solve it:
i added onClick on the button
<button onClick={this.resetSearch}>Reset</button>
Then in the function i put handleSearch to '', by doing this it reset the table:
resetSearch = () =>{
this.handleSearch('')
}

React - Render Component between two existing ones

I am pretty new on using React, what i'm trying to build is a dynamic form in which user can add/remove fields, the problems come when rendering after a row (field) is added
Here is my Row Component, which I use as a template to fill by props
class Row extends React.Component {
constructor(props){
super(props);
this.addLine = this.addLine.bind(this)
this.handleTitleChange = this.handleTitleChange.bind(this)
this.handleInquisitionChange = this.handleInquisitionChange.bind(this)
}
state = {
pos: this.props.pos,
title: this.props.title,
inquisition: this.props.inquisition
}
addLine() {
this.props.addLine(this.state.pos);
}
handleTitleChange = async (event) => {
await this.setState({title: event.target.value});
this.props.updateRowState(this.state.pos, this.state.title, "title")
}
handleInquisitionChange = async (event) => {
await this.setState({inquisition: event.target.value});
this.props.updateRowState(this.state.pos, this.state.inquisition, "inquisition")
}
render(){
return(
<div className="w3-row odg-line">
<div className="w3-col m2" style={{paddingRight: "8px"}}>
<input type="text" name="titolo[]" placeholder="Argomento" style={{width:"100%"}} onChange={this.handleTitleChange} required/>
</div>
<div className="w3-col m4" style={{paddingRight: "8px"}}>
<textarea form="convocazione" name="istruttoria[]" placeholder="Istruttoria" style={{width:"100%"}} onChange={this.handleInquisitionChange} required></textarea>
</div>
<div className="w3-col m1">
<button type="button" style={{padding:0, height: "24px", width: "24px"}} className="w3-red w3-button w3-hover-white" onClick={() => this.addLine()}>+</button>
</div>
</div>
)
}
}
And this is its parent Convoca, as you can see by its addLine method whenever a "plus" button is pressed it pushes a row after that and updates component state, as far as I know this should cause the component to render again but when it comes it just adds the new one after the already rendered ones
class Convoca extends React.Component {
constructor(props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this);
this.addLine = this.addLine.bind(this);
}
state = {
rows: [
{pos:0, title: "", inquisition: ""},
{pos:1, title: "", inquisition: ""}
]
}
async addLine(position){
let buffer = this.state.rows;
buffer.splice(position+1, 0, {pos: position+1, title: "", inquisition: ""})
for(let i = position+2; i<buffer.length; i++){
buffer[i].pos++;
}
await this.setState({rows: buffer})
}
handleChangeState = async (pos, val, field) => {
let buffer = this.state.rows;
if(field === "title") buffer[pos].title = (field === "title" ? val : null);
if(field === "inquisition") buffer[pos].inquisition = (field === "inquisition" ? val : null);
await this.setState({rows: buffer})
}
handleSubmit(){
console.log("submitted")
}
render() {
return(
<div className="w3-main" style={{marginLeft:"340px", marginRight:"40px"}}>
<form action="/convocazione" id="convocazione">
{ this.state.rows.map((row) => (
<Row updateRowState={(pos, val, field) => this.handleChangeState(pos, val, field)} addLine={(pos)=>this.addLine(pos)} pos={row.pos} title={row.title} inquisition={row.inquisition}></Row>)
) }
<input className="w3-red w3-button w3-hover-white" type="submit" value="Convoca"/>
</form>
</div>
);
}
}
I would implement addLine function another way
Take a look at the snippet.
const createElement = React.createElement;
class Row extends React.Component {
render() {
const {
position
} = this.props;
return createElement('div', null, [
createElement('input', {
type: "text",
value: this.props.title
}),
createElement('button', {
type: "button",
onClick: () => this.props.onAdd(position)
}, '+')
]);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
rows: [{
id: 0,
position: 0,
title: 'id 0 position 0'
},
{
id: 1,
position: 1,
title: 'id 1 position 1'
},
]
};
this.addLine = this.addLine.bind(this);
}
addLine(position) {
const {
rows
} = this.state
const newId = rows.reduce((acc, row) => acc > row.id ? acc : row.id, 0) + 1
position = position + 1;
const newRows = [
...rows.filter(row => row.position < position),
{
id: newId,
position,
title: `id ${newId} position ${position}`
},
...rows.filter(row => row.position >= position).map(row => ({ ...row,
position: row.position + 1,
title: `id ${row.id} position ${row.position + 1}`
}))
]
newRows.sort((prev, next) => prev.position - next.position)
this.setState({
rows: newRows
})
}
render() {
const items = this.state.rows.map(item =>
createElement(Row, {
key: item.id,
title: item.title,
position: item.position,
onAdd: this.addLine
})
)
return createElement('form', null, items);
}
}
var rootElement = createElement(App, {}, )
ReactDOM.render(rootElement, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">
</div>
Make sure every Row has key prop with unique id

React : Updated values is not coming in React-popup

I am working on React-popup but I face some problem . I set condition if user select 3rd option then I am updating state value . State value is updated, When I console it in render then it showing updated value but when I want to use it in React-PopUp updated value is not working . I need to re-render a content on pop-up form if state is get updated . I am new please help me .
Note: PopUp form will be show on click
Code
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import MyCalendar from 'react-big-calendar';
import CustomToolbar from './toolbar';
import Popup from 'react-popup';
import Input from './input';
import axios from 'axios'
import moment from 'moment';
import { fetchEvents, createEvent, updateEvent, deleteEvent } from '../../actions/calendar';
// Setup the localizer by providing the moment (or globalize) Object to the correct localizer.
const localizer = MyCalendar.momentLocalizer(moment); // or globalizeLocalizer
class Calendar extends Component {
constructor(){
super();
this.state={
isCustomer:false,
}
}
onChangeHandler = ev => {
this.setState(
{isCustomer:ev.target.value === "viewing"},
() => { console.log(this.state.isCustomer)
})
}
componentDidMount() {
this.props.fetchEvents();
}
//RENDER SINGLE EVENT POPUP CONTENT
renderEventContent(slotInfo) {
const date = moment(slotInfo.start).format('MMMM D, YYYY');
return (
<div>
<p>Date: <strong>{date}</strong></p>
<p>Subject: {slotInfo.taskChage}</p>
<p>Time : {slotInfo.time}</p>
<p>Date : { slotInfo.date}</p>
<p>Notes : {slotInfo.notes}</p>
<p>User Id : {slotInfo.userId}</p>
</div>
);
}
//ON SELECT EVENT HANDLER FUNCTION
onSelectEventHandler = (slotInfo) => {
console.log("New Applicaiton ", this.state.isCustomer)
Popup.create({
title: slotInfo.title,
content: this.renderEventContent(slotInfo),
buttons: {
right: [{
text: 'Edit',
className: 'info',
action: function () {
Popup.close(); //CLOSE PREVIOUS POPUP
this.openPopupForm(slotInfo); //OPEN NEW EDIT POPUP
}.bind(this)
}, {
text: 'Delete',
className: 'danger',
action: function () {
//CALL EVENT DELETE ACTION
this.props.deleteEvent(slotInfo.id);
Popup.close();
}.bind(this)
}]
}
});
}
//HANDLE FUNCITON ON SELECT EVENT SLOT
onSelectEventSlotHandler = (slotInfo) => {
this.openPopupForm(slotInfo); //OPEN POPUP FOR CREATE/EDIT EVENT
}
//POPUP-FORM FUNCTION FOR CREATE AND EDIT EVENT
openPopupForm = (slotInfo) => {
let newEvent = false;
let popupTitle = "Update Event";
if(!slotInfo.hasOwnProperty('id')) {
slotInfo.subject = null;
slotInfo.taskType = null;
slotInfo.time=null;
slotInfo.date=null;
slotInfo.notes=null;
slotInfo.userId=null;
popupTitle = "Add task to Diary";
newEvent = true;
}
let titleChange = function (value) {
slotInfo.subject = value;
};
let taskChange = function (value) {
slotInfo.taskType = value;
};
let timeChange = function (value) {
slotInfo.time = value;
};
let dateChnage = function ( value){
slotInfo.date=value;
};
let notesChange = function ( value){
slotInfo.notes=value;
};
let userId = function ( value){
slotInfo.userId=value;
};
Popup.create({
title: popupTitle,
content: <div>
<Input fieldName="subject" onChange={titleChange} placeholder="Subject" />
<select name="taskType" onChange={this.onChangeHandler}>
<option vlaue="no">Task Type</option>
<option value="meeting">Meeting</option>
<option value="followup">Follow Up</option>
<option value="viewing">Viewing</option>
<option value="reminder">Reminder</option>
<option value="other">Other</option>
</select>
{this.state.isCustomer===true && <input defaultValue="Hi customer :)"></input>}
<Input fieldName="time" onChange={timeChange} placeholder="Time"/>
<Input fieldName="date" onChange={dateChnage} placeholder="Date"/>
<Input fieldName="notes" onChange={notesChange} placeholder="Notes"/>
<Input fieldName="userId" onChange={userId} placeholder="User Id"/>
</div>,
buttons: {
left: ['cancel'],
right: [{
text: 'Save',
className: 'success',
action: function () {
//CHECK THE ID PROPERTY FOR CREATE/UPDATE
if(newEvent) {
this.props.createEvent(slotInfo); //EVENT CREATE ACTION
} else {
this.props.updateEvent(slotInfo); //EVENT UPDATE ACTION
}
Popup.close();
}.bind(this)
}]
}
});
}
//EVENT STYLE GETTER FOR SLYLING AN EVENT ITEM
eventStyleGetter(event, start, end, isSelected) {
let current_time = moment().format('YYYY MM DD');
let event_time = moment(event.start).format('YYYY MM DD');
let background = (current_time>event_time) ? '#DE6987' : '#8CBD4C';
return {
style: {
backgroundColor: background
}
};
}
render() {
return (
<div className="calendar-container">
<MyCalendar
popup
selectable
localizer={localizer}
defaultView={MyCalendar.Views.MONTH}
components={{toolbar: CustomToolbar}}
views={['month']}
style={{height: 600}}
events={this.props.events}
eventPropGetter={(this.eventStyleGetter)}
onSelectEvent={(slotInfo) => this.onSelectEventHandler(slotInfo)}
onSelectSlot={(slotInfo) => this.onSelectEventSlotHandler(slotInfo)}
/>
<Popup />
</div>
);
}
}
function mapStateToProps(state) {
return {
events: state.events
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
fetchEvents,
createEvent,
updateEvent,
deleteEvent
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Calendar);
Try to use react inbuild method componentDidUpdate(). The componentDidUpdate is particularly useful when an operation needs to happen after the DOM is updated and the update queue is emptied
import React, { Component } from "react";
import ReactDom from "react-dom";
import { Modal, Button, Row, Col, Form } from "react-bootstrap";
class PopupModal extends React.Component {
popupShown = true;
componentWillMount() {
}
componentDidUpdate() { //called when state update in parent component
this.setState({ modalData: null });
this.setState({ modalData: this.props.modalData});
this.popupShown = true;
}
state = {
modalData: this.props.modalData //getting data for the modal from parent
};
onHidePopup = () => {
this.setState({ modalData: null });
this.popupShown = false;
};
render() {
if (this.popupShown == true) {
return (
<Modal
show={this.popupShown}
onHide={this.onHidePopup}
>
<Modal.Header closeButton>
<Modal.Title id="modalTitle">Model header</Modal.Title>
</Modal.Header>
<Modal.Body>
Model body comes here
</Modal.Body>
<Modal.Footer>
<p>Hello I am Footer</p>
</Modal.Footer>
</Modal>
);
} else {
return <div />;
}
}
}
export default PopupModal;

Error rendering react component (object instead of string)

I have a problem rendering a component with react. I'm trying to code a wizard, however I get the following error when rendering Mstep1.
Element type is invalid: expected a string (for built-in components) or a hereclass/function (for composite components) but got: object. You herelikely forgot to export your component from the file it's defined in.
To better explain, here is some code:
-- wizard.js --
import React, { Component } from 'react';
import { Mstep1, Mstep2 } from './Steps'
import { states } from './States'
import { StateMachine } from './StateMachine.js';
class Wizard extends Component {
constructor(props) {
super(props);
this.state = {
currentState: states.MSTEP1,
formSaves: [],
}
this.saveForm =this.saveForm.bind(this);
this.nextStep = this.nextStep.bind(this);
this.backStep = this.backStep.bind(this);
this.stateMachine = new StateMachine();
}
saveForm(formSave) {
let formSaves = this.state.formSaves.concat();
formSaves.push(formSave);
this.setState({
formSaves: formSaves
});
}
nextStep(desiredState) {
let currentState = this.state.currentState;
let nextState = this.stateMachine.transitionTo(currentState, desiredState);
this.setState({
currentState: nextState
});
}
backStep(desiredState) {
let currentState = this.state.currentState;
this.setState({
currentState: this.stateMachine.transitionFrom(currentState, desiredState)
});
}
//Switch Case Methode um den CurrentStep zu bestimmen
currentStep() {
console.log(this.state.currentState);
// console.log(typeof this.state.currentState);
switch (this.state.currentState) {
case states.MSTEP1:
console.log(typeof states.MSTEP1);
return <Mstep1
saveForm={this.save}
back={this.backStep}
next={this.nextStep}
/>;
break;
case states.MSTEP2:
return(<Mstep2
/>);
default:
break;
}
}
render() {
return (
<div>
{this.currentStep()}
</div>
);
}
}
export default Wizard;
--Steps.js---
import React, { Component } from 'react';
import { states } from './States.js';
import TextArea from './Select';
import SingleInput from './SingleInput';
// import Select from './Select';
export class Mstep1 extends Component {
constructor(props) {
super(props);
this.state = {
modultitel: '',
startdate: '',
enddate: '',
modulkuerzel: '',
modulDescription: ''
};
//Bindings
this.handleModultitel = this.handleModultitel.bind(this);
this.handleStartdate = this.handleStartdate.bind(this);
this.handleEnddate = this.handleEnddate.bind(this);
this.handleModulkuerzel = this.handleModulkuerzel.bind(this);
this.handlemodulDescriptionChange = this.handlemodulDescriptionChange.bind(this);
this.validate = this.validate.bind(this);
}
handleModultitel(e) {
this.setState({ modultitel: e.target.value }, () => console.log('modultitel:', this.state.modultitel));
}
handleStartdate(e) {
this.setState({ startdate: e.target.value }, () => console.log('startdate:', this.state.startdate));
}
handleEnddate(e) {
this.setState({ enddate: e.target.value }, () => console.log('enddate:', this.state.enddate));
}
handleModulkuerzel(e) {
this.setState({ modulkuerzel: e.target.value }, () => console.log('modulkuerzel', this.state.modulkuerzel));
}
handlemodulDescriptionChange(e) {
// const textArray = e.target.value.split('').filter(x => x !== 'e');
// console.log('string split into array of letters',textArray);
// const filteredText = textArray.join('');
// this.setState({ modulDescription: filteredText }, () => console.log('modulDescription', this.state.modulDescription));
this.setState({ modulDescription: e.target.value }, () => console.log('modulDescription', this.state.modulDescription));
}
handleClearForm(e) {
e.preventDefault();
this.setState({
modultitel: '',
startdate: '',
enddate: '',
modulkuerzel: '',
modulDescription: ''
});
}
validate(e) {
e.preventDefault();
this.props.saveForm({
modultitel: '',
startdate: '',
enddate: '',
modulkuerzel: '',
modulDescription: '',
});
this.props.next(this.props.nextState);
this.handleClearForm(e);
}
render() {
return (
<form>
<h5>Modul anlegen (Schritt 1 von x)</h5>
<SingleInput
inputType={'text'}
title={'Modultitel: '}
name={'name'}
controlFunc={this.handleModultitel}
content={this.state.modultitel}
placeholder={'Modultitel'} />
<SingleInput
inputType={'text'}
title={'Gültig ab: '}
name={'Startdate'}
controlFunc={this.handleStartdate}
content={this.state.startdate}
placeholder={'Startdatum'} />
<SingleInput
inputType={'text'}
title={'Gültig bis: '}
name={'Enddate'}
controlFunc={this.handleEnddate}
content={this.state.enddate}
placeholder={'Enddatum'} />
<SingleInput
inputType={'text'}
title={'Modulkürzel'}
name={'Modulkürzel'}
controlFunc={this.handleModulkuerzel}
content={this.state.modulkuerzel}
placeholder={'Modulkützel'} />
<TextArea
title={'Kurzbeschreibung'}
rows={5}
name={'Kurzbeschreibung'}
resize={false}
content={this.state.modulDescription}
controlFunc={this.handlemodulDescriptionChange}
placeholder={'Kurzbeschreibung zu Modulen'} />
<button
onClick={this.validate}>Weiter</button>
<button
onClick={this.handleClearForm}>Clear form</button>
</form>
);
}
}// Ende Class Mstep1
export class Mstep2 extends Component {
constructor(props) {
super(props);
this.state = {
modulThema: '',
themaDescription: ''
};
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleThemaDescription = this.handleThemaDescription.bind(this);
this.back = this.back.bind(this);
}
handleModulthema(e) {
this.setState({ modulThema: e.target.value }, () => console.log('thema: ', this.state.modulThema));
}
handleThemaDescription(e) {
this.setState({ themaDescription: e.target.value }, () => console.log('tDescription', this.state.themaDescription))
}
back(e) {
e.preventDefault();
this.props.back(states.MSTEP1);
}
validate(e) {
e.preventDefault();
this.props.saveForm({
modulThema: '',
themaDescription: ''
});
this.props.next(this.props.nextState);
this.handleClearForm(e);
}
render() {
return (
<form>
<h5>Modul anlegen (Schritt 2 von x)</h5>
<SingleInput
inputType={'text'}
title={'Neues Thema'}
name={'modulname'}
controlFunc={this.handleModulThema}
content={this.modulThema}
placeholder={'Modulthema'} />
<TextArea
title={'Beschreibung (Inhalte des Thmas)'}
rows={5}
name={'Thema-Beschreibung'}
resize={10}
controlFunc={this.handleThemaDescription}
content={this.state.themaDescription}
placeholder={''} />
<button
onClick={this.validate}>Weiter</button>
<button
onClick={this.back}>zurück</button>
<button
onClick={this.handleClearForm}>Clear form</button>
</form>
);
}
}
I would recommend you to split Mstep1 and Mstep2 into two different files and then you can export default class Mstep1 for example and import with import Mstep1 from 'Steps/Mstep1'. It's a good practice in React that you stick to one component per file. Refer to this article as a good reference to organize your react applications.
You can do export const class Mstep1 and export const Mstep2. So that you can import it like you already have.

Categories

Resources