How to render method from handle submit of a stateful component - javascript

I am trying to redirect a page on datepicker submit, the problem is I get Unexpected token expected ";"
I have tried suggestions from users and React Docs as well as Datepicker Docs This is where I am now coming from In JSX How to redirect on Handlesubmit from DataPicker? But when applied to my code I get the error
./src/components/Toolbar/SearchCard/Datepicker/Datepicker.jsx
Line 42: Parsing error: Unexpected token, expected ";"
40 | }
41 | state = {};
> 42 | render() {
| ^
43 | return (
44 | <>
45 | <FormGroup>
Here is the whole file
import React from "react";
import "./Datepicker.css";
import "./Btnsearch/Btnsearch";
// react plugin used to create datetimepicker
import ReactDatetime from "react-datetime";
// reactstrap components
import {
FormGroup,
InputGroupAddon,
InputGroupText,
InputGroup,
Col,
Row
} from "reactstrap";
import Btnsearch from "./Btnsearch/Btnsearch";
class Datepicker extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit = event => {
event.preventDefault();
this.setState({wasSubmitted: true});
}
render() {
const { value, wasSubmitted } = this.state;
if (wasSubmitted) {
return <Redirect to='/Bookingpage' />
} else {
return //... your normal component
}
}
}
state = {};
render() {
return (
<>
<FormGroup>
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText
>
<i className="ni ni-calendar-grid-58" />
</InputGroupText>
</InputGroupAddon>
<ReactDatetime
value={this.state.value}
onChange={this.handleChange}
inputProps={{
placeholder: "Date Picker Here"
}}
timeFormat={false}
/>
</InputGroup>
</FormGroup>
<form onSubmit={this.handleSubmit}>
<Btnsearch type="submit" value={this.state.value}/>
</form>
</>
);
}
}
export default Datepicker;
I expect the app to render the hanndleSubmit and redirect to a new page

Your exception is because your parser / bundler cannot handle inline properties on the class.
You could try and set that up, however because you are defining state in the constructor, line 41 (state = {};) is not needed.
aka state is assigned to the class instance here
constructor(props) {
super(props);
this.state = {
value: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
In addition to that, this looks like an issue with copy pasting code
You have two render methods in this class with unmatching curly brackets. as you can see here
render() {
const { value, wasSubmitted } = this.state;
if (wasSubmitted) {
return <Redirect to='/Bookingpage' />
} else {
return //... your normal component
}
}
}
state = {};
render() {
return (
This should work
import React from "react";
import { Redirect } from 'react-router-dom';
import "./Datepicker.css";
import "./Btnsearch/Btnsearch";
// react plugin used to create datetimepicker
import ReactDatetime from "react-datetime";
// reactstrap components
import {
FormGroup,
InputGroupAddon,
InputGroupText,
InputGroup,
Col,
Row
} from "reactstrap";
import Btnsearch from "./Btnsearch/Btnsearch";
class Datepicker extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ""
};
// this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit = event => {
event.preventDefault();
this.setState({wasSubmitted: true});
}
render() {
const { value, wasSubmitted } = this.state;
if (wasSubmitted) {
return <Redirect to='/Bookingpage' />
} else {
return (
<>
<FormGroup>
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText
>
<i className="ni ni-calendar-grid-58" />
</InputGroupText>
</InputGroupAddon>
<ReactDatetime
value={this.state.value}
onChange={this.handleChange}
inputProps={{
placeholder: "Date Picker Here"
}}
timeFormat={false}
/>
</InputGroup>
</FormGroup>
<form onSubmit={this.handleSubmit}>
<Btnsearch type="submit" value={this.state.value}/>
</form>
</>
);
}
}
}
export default Datepicker;

Related

ReactJS how to access content output from a component?

I'm currently working on a project that uses QuillJS for a rich text editor. I need to post the rich text content to my backend but I'm not sure how to access the QuillJS output.
In RichTextEditor.js
import React, { Component } from "react";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
class RichTextEditor extends Component {
constructor(props) {
super(props);
// this.formats = formats;
this.state = { text: "" }; // You can also pass a Quill Delta here
this.handleChange = this.handleChange.bind(this);
}
handleChange(value) {
this.setState({ text: value });
const text = this.state;
console.log(text);
}
render() {
return (
<ReactQuill
value={this.state.text}
onChange={this.handleChange}
formats={this.formats}
modules={this.modules}
/>
);
}
}
export default RichTextEditor;
The console.log(text) basically just outputs the content of the rich text editor. Something like this "<p><em>aasdasdasd</em><strong><em>asdasdasdasd</em></strong></p>"
In Post.js
import React, { Component } from "react";
import RichTextEditor from "./RichTextEditor.js";
import "../../css/Post.css";
class Post extends Component {
constructor(props) {
super(props);
this.state = {
question: "",
};
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
console.log(this.state);
};
handleSubmit = (e) => {
e.preventDefault();
const { question } = this.state;
console.log("Question");
console.log(question);
render() {
const { question } = this.state;
return (
<div className="post">
<div className="post__container">
<form onSubmit={this.handleSubmit}>
<div className="post__richTextEditor">
<RichTextEditor value={question} onChange={this.onChange} name="question" />
</div>
</form>
</div>
</div>
);
}
}
export default Post;
I'm trying to update the state of the question but it doesn't seem to be updating. console.log(question) only outputs a single string.
How can I access the same string output from RichTextEditor.js?
Your RichTextEditor component should not handle change, it should only receive props from higher component:
class RichTextEditor extends Component {
constructor(props) {
super(props);
}
render() {
return (
<ReactQuill
value={this.props.value}
onChange={this.props.onChange}
formats={this.formats}
modules={this.modules}
/>
);
}
}
export default RichTextEditor;
Then your Post component pass value and onChange props to RichTextEditor:
class Post extends Component {
constructor(props) {
super(props);
this.state = {
question: "",
};
this.onChange = this.onChange.bind(this);
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
console.log(this.state);
};
handleSubmit = (e) => {
e.preventDefault();
const { question } = this.state;
console.log("Question");
console.log(question);
render() {
const { question } = this.state;
return (
<div className="post">
<div className="post__container">
<form onSubmit={this.handleSubmit}>
<div className="post__richTextEditor">
<RichTextEditor value={question} onChange={this.onChange} name="question" />
</div>
</form>
</div>
</div>
);
}
}
in RichTextEditor.js
handleChange(value) {
this.setState({ text: value });
const text = this.state;
console.log(text);
props.onChange(text); // passing the inner State to parent as argument to onChange handler
}
Now in Post.js
onChange = (newStateString) => {
//this.setState({ [e.target.name]: e.target.value });
console.log(newStateString); // you should get the string here
};

Pass data from input field

I want to take data from an input field and pass it into a to Generate QR code. When I pass the value as a text its work. But can’t pass the input value. Does anyone have a simple example of this working?
import React, {Component} from 'react'
import QrCode from 'react.qrcode.generator'
class DemoEdit extends Component {
constructor() {
super();
this.state = {
topicIn: "",
topicOut:""
};
this.handleChange=this.handleChange.bind(this);
this.generate=this.generate.bind(this);
}
handleChange ({ target}){
this.setState({
[target.name] : target.value
})
}
generate(){
this.setState({
topicOut:this.state.topicIn
})
}
render() {
return <div>
<input
type="text"
name="topicIn"
placeholder="Enter Text Here..."
value={this.state.topicIn}
onChange={this.handleChange}
/>
<button value="Send" onClick={this.generate}>Generate</button>
<p>{this.state.topicOut}</p>
<QrCode value={this.state.topicOut}/>
</div>
}
}
export default DemoEdit;
Use a different package. I just tried qrcode.react
import React, { Component } from "react";
import QrCode from "qrcode.react";
class DemoEdit extends Component {
constructor() {
super();
this.state = {
topicIn: ""
};
this.handleChange = this.handleChange.bind(this);
}
handleChange({ target }) {
console.log("value", target.value);
this.setState({
topicIn: `${target.value}`
});
}
render() {
return (
<div>
<input
type="text"
name="topicIn"
placeholder="Enter Text Here..."
value={this.state.topicIn}
onChange={this.handleChange}
/>
<QrCode value={this.state.topicIn} />
</div>
);
}
}
export default DemoEdit;
or as a more fancy functional component with hooks, which I totally recommend to use
import React, { useState } from "react";
import QrCode from "qrcode.react";
const DemoEdit = () => {
const [topicIn, setTopicIn] = useState("");
const onChange = (event) => setTopicIn(event.target.value);
return (
<div>
<input
type="text"
name="topicIn"
placeholder="Enter Text Here..."
value={topicIn}
onChange={onChange}
/>
<QrCode value={topicIn} />
</div>
);
};
export default DemoEdit;

Why the state is not updating in App.js after setting up this.setState?

Here is my simple to-do app program where I have made only one component which takes in the input form user and passes that input value to App.js to update items in App.js state.
todo-form.component.js
import React from 'react';
class SignInForm extends React.Component {
constructor(){
super();
this.state ={
temp: null
};
}
handleChange = (e) => {
e.preventDefault();
this.setState({
temp: e.target.value
},
console.log(this.state)
);
// this.props.addInput(e.target.value);
}
handleSubmit= (e) => {
e.preventDefault();
console.log(this.state.temp);
this.props.addInput(this.state.temp);
}
render(){
return(
<div className="container-form">
<form onSubmit={this.handleSubmit}>
<input
name="description"
type="text"
placeholder="add description"
onChange={this.handleChange}
value={this.state.input}
/>
<button type="submit">ADD</button>
</form>
</div>
);
}
}
export default SignInForm;
App.js
import React from 'react';
import './App.css';
import SignInForm from './components/todo-form/todo-form.component'
import ItemList from './components/todo-list/todo-list.component';
class App extends React.Component {
constructor(){
super();
this.state = {
input: []
};
}
addInput = (item) => {
let newInput=[...this.state.input,item];
console.log(newInput);
this.setState = ({
input: newInput
},
console.log(this.state)
);
}
render(){
return (
<div className="App">
<h1>TO-DO LIST</h1>
<SignInForm addInput={this.addInput} />
</div>
);
}
}
export default App;
On taking input the state inside todo-form.component.js is getting updated with the typed input value but on passing state.temp in handleChange function, the state inside App.js is not updating when addInput function is called.
Please help me on this issue and how my state is not getting updated in App.js??
Your setState is the problem. Have a look at my code.
App.js
class App extends React.Component {
state = {
input: [],
};
addInput = (item) => {
let newInput = [...this.state.input, item];
//setState should be this way
this.setState({
input: newInput,
});
};
render() {
return (
<div className="App">
<h1>TO-DO LIST</h1>
{this.state.input.map((el) => (
<li> {el}</li>
))}
<SignInForm addInput={this.addInput} />
</div>
);
}
}
export default App;
Login file.
class SignInForm extends React.Component {
// constructor(props) {
// super(props);
state = {
temp: null,
};
// }
handleChange = (e) => {
e.preventDefault();
this.setState({
temp: e.target.value,
});
// this.props.addInput(e.target.value);
};
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state.temp);
this.props.addInput(this.state.temp);
};
render() {
return (
<div className="container-form">
<form onSubmit={this.handleSubmit}>
<input
name="description"
type="text"
placeholder="add description"
onChange={this.handleChange}
value={this.state.input}
/>
<button type="submit">ADD</button>
</form>
</div>
);
}
}
export default SignInForm;

React-select is not send in the request payload

I'm using react-select with react-bootstrap, but it don't send the selected options in the select to the request payload, it only sends the first two inputs
I've tried lots of props as you can see in the code, but when I check the request payload it doesn't send the select
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Form from 'react-bootstrap/Form'
import Container from 'react-bootstrap/Container'
import Row from 'react-bootstrap/Row'
import Col from 'react-bootstrap/Col'
import Button from 'react-bootstrap/Button'
import Select from 'react-select'
export default class CreateMembro extends Component {
constructor(props) {
super(props)
this.state = {mem_nome: '', mem_data_nascimento: '', selectedOption: null, opcoes: []}
this.handleFormInput = this.handleFormInput.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
}
getHostName() {
return `http://${window.location.hostname}`
}
componentDidMount() {
axios.get(`${this.getHostName()}/get-all-ministerios`).then((res) => {
let response = []
res.data.map(r => {
r.value = r.min_nome
r.label = r.min_descricao
delete r.min_nome
delete r.min_descricao
delete r.min_id
delete r.created_at
delete r.updated_at
response.push(r);
})
this.setState({ opcoes: response})
})
}
handleChange(selectedOption) {
this.setState({ selectedOption });
console.log(selectedOption)
}
handleSubmit(event) {
event.preventDefault()
const dataForm = {
mem_nome : this.state.mem_nome,
mem_data_nascimento : this.state.mem_data_nascimento
}
axios.post(`${this.getHostName()}/membros`, dataForm).then((response) => {
console.log(response.data)
}).catch((error)=>{
console.log(error)
})
}
handleFormInput(event) {
this.setState({
[event.target.id]: event.target.value
})
console.log(event.target.id+'--'+event.target.value)
}
render() {
return (
<Container>
<Row>
<Col md={6}>
<Form onSubmit={this.handleSubmit}>
<Form.Group>
<Form.Label>Nome do Membro</Form.Label>
<Form.Control id="mem_nome" type="text" placeholder="Nome do Membro" onChange={value = handleFormInput(value)} />
<Form.Label>Data de Nascimento</Form.Label>
<Form.Control id="mem_data_nascimento" type="date" placeholder="Data de Nascimento" onChange={value = handleFormInput(value)}/>
<Form.Label >Ministérios</Form.Label>
<Select
id="minid"
name="asdasd89NAMEEE"
ref="refsid"
inputId={"minresss"}
inputId="ministerios"
controlId="sdasd78gd"
isMulti={true}
labelKey="labelkeu"
isSearchable={true}
value={this.state.selectedOption}
onChange={value = handleChange(value)}
options={this.state.opcoes}
placeholder="Selecione o(s) ministério(s)">
</Select>
</Form.Group>
<Button type="submit" variant="primary">
Enviar
</Button>
</Form>
</Col>
</Row>
</Container>
);
}
}
I expect that the select values goes into the request payload.
I'm using the same library like you so you can take a look at mine code
I think your code should be change to something like this
change from this
onChange={value = handleChange(value)}
to this
onChange={value => handleChange(value)}
and
const dataForm = {
mem_nome : this.state.mem_nome,
mem_data_nascimento : this.state.mem_data_nascimento,
selectedOption: this.state.selectedOption // you missing this
}

How to hide some component based on some flag in react js

I want to hide some component based on some flag in react js.
I have an App component where I have Login and other components, I want to hide the other component until Login components this.state.success is false and on click of a button I am changing the sate, but it's not working, I am new to react,
My App Class compoenent -
import React, { Component } from "react";
import logo from "../../logo.svg";
// import Game from "../Game/Game";
import Table from "../Table/Table";
import Form from "../Table/Form";
import Clock from "../Clock/Clock";
import "./App.css";
import Login from "../Login/Login";
class App extends Component {
state = {
success: false
};
removeCharacter = index => {
const { characters } = this.state;
this.setState({
characters: characters.filter((character, i) => {
return i !== index;
})
});
};
handleSubmit = character => {
this.setState({ characters: [...this.state.characters, character] });
};
handleSuccess() {
this.setState({ success: true });
}
render() {
const { characters, success } = this.state;
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<span className="Span-inline">App</span>
<Clock time={new Date()} />
</header>
<Login success={success} handleSuccess={this.handleSuccess} />
{success && (
<div className="container">
<h1>React Tutorial</h1>
<p>Add a character with a name and a job to the table.</p>
<Table
characterData={characters}
removeCharacter={this.removeCharacter}
/>
<h3>Add New character</h3>
<Form handleSubmit={this.handleSubmit} />
</div>
)}
{/* <Game /> */}
</div>
);
}
}
export default App;
My Login component -
import React, { Component } from "react";
import Greeting from "./Greeting";
import LogoutButton from "./LogoutButton";
import LoginButton from "./LoginButton";
class Login extends Component {
constructor(props) {
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = {
isLoggedIn: false,
name: "",
success: false
};
}
handleLoginClick() {
this.setState({ isLoggedIn: true });
this.setState({ success: true });
}
handleLogoutClick() {
this.setState({ isLoggedIn: false });
this.setState({ success: false });
}
onChange = e => {
this.setState({
name: e.target.value
});
};
render() {
const isLoggedIn = this.state.isLoggedIn;
const name = this.state.name;
// const successLogin = this.state.success;
let button;
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting
isLoggedIn={isLoggedIn}
name={name}
onChange={this.onChange}
/>
{button}
</div>
);
}
}
export default Login;
please guide me on what I am doing wrong.
Why sometime debuggers do not trigger in react component?
For the sake of example I have used functional stateless component here. You can use Class component all upto you.
const conditionalComponent = (props) => {
let condition = true;
return (
{condition && <div><h1>Hello world</h1></div>}
}
Instead of directly giving condition you can even call function which returns a boolean value.
handleLoginClick() {
this.setState({ isLoggedIn: true });
this.setState({ success: true });
this.props.handleSuccess()
}
do like this
<Login success={success} handleSuccess=
{this.handleSuccess} />
bind this function

Categories