Getting Data From React-Bootstrap Input - reactjs

I am not finding good docs or videos on how to get data from my inputs with React-Bootstrap. I want to be able to click the button and then bring what I typed into the input box into my onClick function.
import React from "react";
import Button from 'react-bootstrap/Button';
import './Search.css';
import InputGroup from 'react-bootstrap/InputGroup';
import FormControl from 'react-bootstrap/FormControl';
class search extends React.Component {
constructor(props){
super(props);
this.text = React.createRef();
this.searchChar = this.searchChar.bind(this);
}
searchChar = () => {
console.log("Button Clicked")
const value = this.input.current.value;
console.log(value)
}
render() {
return (
<div className="searchBar">
<form>
<InputGroup className="mb-3">
<InputGroup.Prepend>
<InputGroup.Text id="basic-addon1">Character Search</InputGroup.Text>
</InputGroup.Prepend>
<FormControl ref = {this.input}
placeholder="Character Name"
aria-label="Character Name"
aria-describedby="basic-addon1"
/>
</InputGroup>
<Button onClick={this.searchChar(this.input)} variant="outline-danger">Search </Button>
</form>
</div>
);
}
}
export default search;

Just try to write your input values in state
for example;
import React from "react";
import Button from 'react-bootstrap/Button';
import './Search.css';
import InputGroup from 'react-bootstrap/InputGroup';
import FormControl from 'react-bootstrap/FormControl';
class search extends React.Component {
constructor(props){
super(props);
this.state = {
basicAddon1 : null,
};
}
searchChar = () => {
console.log("Button Clicked")
const value = this.state.basicAddon1;
console.log(value)
}
render() {
return (
<div className="searchBar">
<form>
<InputGroup className="mb-3">
<InputGroup.Prepend>
<InputGroup.Text id="basic-addon1">Character Search</InputGroup.Text>
</InputGroup.Prepend>
<FormControl
placeholder="Character Name"
aria-label="Character Name"
aria-describedby="basic-addon1"
onChange={event => {
this.setState({
basicAddon1 : event.target.value
});
}}
value={this.state.basicAddon1 ? this.state.basicAddon1 : ""}
/>
</InputGroup>
<Button onClick={this.searchChar(this.input)} variant="outline-danger">Search </Button>
</form>
</div>
);
}
}
export default search;
you can create inputChangeHandler function or something else for improve your code
it just basic

The same way you deal with getting data from a form in pure React, you do with react-bootstrap. This answer here shows many options to do so.
My favourite approach among those options is this one. Using that approach your code would be something like:
class search extends React.Component {
constructor(props) {
super(props)
this.handleSave = this.handleSave.bind(this)
}
onChange(event) {
// Intended to run on the change of every form element
event.preventDefault()
this.setState({
[event.target.name]: event.target.value,
})
}
handleSave() {
console.log(`Do something with : {this.state.characterName}`)
}
render() {
return (
<div className="searchBar">
<form>
<InputGroup className="mb-3">
<InputGroup.Prepend>
<InputGroup.Text id="basic-addon1">
Character Search
</InputGroup.Text>
</InputGroup.Prepend>
<FormControl
name="characterName"
placeholder="Character Name"
aria-label="Character Name"
aria-describedby="basic-addon1"
onChange={this.onChange.bind(this)}
/>
</InputGroup>
<Button onClick={this.handleSave} variant="outline-danger">
Search{' '}
</Button>
</form>
</div>
)
}
}

Related

Input react wrapper

I want to make a form for user data and I was asked to make a wrapper react components for each type of input. My problem is passing the handler to the input component.
This is my form:
import React from 'react';
import {addUser as addNewUser} from '../../services/index';
import {TextBox} from './TextBox'
interface AddUserProps{
}
interface AddUserState{
UserName:string,
}
export default class AddUser extends React.Component<AddUserProps, AddUserState> {
constructor(props:any) {
super(props);
this.state = {
UserName: '',
};
this.updateUserName = this.updateUserName.bind(this);
}
updateUserName(event: React.ChangeEvent<HTMLInputElement>) {
this.setState({UserName: event.target.value});
}
handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
console.log(this.state)
addNewUser(this.state)
}
render() {
return (
<div>
<form
className = "user-add-form"
onSubmit={(event) => this.handleSubmit(event)}
>
<h3>Adauga utilizatori:</h3>
<label htmlFor="userName">User Name:</label>
<TextBox name="userName" type="text" value={userName} handleChange={this.updateUserName}/>
<input type="submit" value="Add user"/>
</form>
</div>
)
}
}
export {AddUser};
And this is the input component that I made:
import React from 'react'
export function TextBox(props) {
return (
<div>
<input type={props.type}
name={props.name}
value={props.value}
onChange={(event) => props.HandleInput(event)}
/>
</div>
)
}
So what I don't know is how to pass the event handler to the input component, because as it is right now it can't find it.
It should exist in Textbox's props as handleChange as it's passed in the parent component. Does this not work?
<input
type={props.type}
name={props.name}
value={props.value}
onChange={(event) => props.handleChange(event)}
/>

React Js Login Beginner

first of all I am a very beginner at React.js. I am creating my super simple static code which has to login the user by the credentials provided in the state and redirect to homepage. But for some reason it doesn't work and doesn't redirect me to the homepage, which has the route of '/', btw my Login route is '/login'. I would appreciate any help. Here is my code:
import React from 'react';
import TextField from '#material-ui/core/TextField';
import { makeStyles } from '#material-ui/core/styles';
import Typography from '#material-ui/core/Typography';
import Container from '#material-ui/core/Container';
import Button from '#material-ui/core/Button';
import HomePage from './HomePage';
import { Redirect } from 'react-router-dom';
class LoginPage extends React.Component {
constructor(props) {
super(props);
this.state = {
loginData: {
username: 'test',
password: 'test'
},
errors: {}
};
this.buttonClickHandle = this.buttonClickHandle.bind(this);
this.loginHandle = this.loginHandle.bind(this);
}
loginHandle(event) {
let field = event.target.name;
let value = event.target.value;
let loginData = this.state.loginData;
loginData[field] = value;
this.setState({loginData: loginData});
}
buttonClickHandle(event) {
event.preventDefault();
if ( this.state.loginData.username === this.target.username) {
console.log("User exists. Go to the login page");
return <Redirect to="/"/>
} else {
console.log("User doesn't exists. Show error message");
}
}
render() {
return (
<div className="loginPage">
<Container maxWidth="sm">
<h2>Login</h2>
<form noValidate autoComplete="off" onChange={this.loginHandle}>
<div className="loginForm">
<TextField
required
id="outlined-required"
label="E-mail"
variant="outlined"
placeholder="Your e-mail..."
className="loginInput"
/>
<TextField
required
id="outlined-password-input"
label="Password"
type="password"
autoComplete="current-password"
variant="outlined"
placeholder="Your password..."
className="loginInput"
/>
<Button
variant="contained"
color="primary"
onClick={this.buttonClickHandle}
>
Login
</Button>
</div>
</form>
</Container>
</div>
)
}
}
export default LoginPage
There are some things that look off in your code.
There is no onChange prop in forms only onSubmit
The button should trigger the onSubmit function, this is done by setting the type of the button as submit
To get the input values from the form you need to put a name and get them as event.target.name.value inside the onSubmit function
here is a working example of your code
class LoginPage extends React.Component {
constructor(props) {
super(props);
this.state = {
loginData: {
username: "test",
password: "test"
},
errors: {}
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
if (
this.state.loginData.username === event.target.username.value &&
this.state.loginData.password === event.target.password.value
) {
console.log("User exists. Go to the login page");
return <Redirect to="/" />;
} else {
console.log("User doesn't exists. Show error message");
}
}
render() {
return (
<div className="loginPage">
<Container maxWidth="sm">
<h2>Login</h2>
<form noValidate autoComplete="off" onSubmit={this.handleSubmit}>
<div className="loginForm">
<TextField
required
name="username"
id="outlined-required"
label="E-mail"
variant="outlined"
placeholder="Your e-mail..."
className="loginInput"
/>
<TextField
required
name="password"
id="outlined-password-input"
label="Password"
type="password"
autoComplete="current-password"
variant="outlined"
placeholder="Your password..."
className="loginInput"
/>
<Button variant="contained" color="primary" type="submit">
Login
</Button>
</div>
</form>
</Container>
</div>
);
}
}
export default LoginPage;

react-bootstrap - Form.Control defaultValue not updated when re-rendered

When I call setState and my form is re-rendered, the value of the text input doesn't change.
import React, { Component } from 'react';
import { Button, Col, Form, Row } from 'react-bootstrap';
export default class Test extends Component {
constructor(props) {
super(props);
this.state = {
status: "new"
}
}
approve = (e) => {
this.setState({
status: "I'm newer than you!"
});
e.preventDefault();
}
render() {
return (
<div>
Status is {this.state.status}
<Form onSubmit={this.approve}>
<Form.Group as={Row} controlId="status">
<Form.Label column >Status</Form.Label>
<Col>
<Form.Control readOnly type="text" size="sm" defaultValue={this.state.status} />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Button type="submit">approve</Button>
</Form.Group>
</Form>
</div>
);
}
}
When I click on the button, I see the static text ("Status is ...") get updated but the input field does not. Have I wrongly assumed the text input should update?
If you want to change it, you can replace 'defaultValue' with 'value' in FormControl component.
<Form.Control readOnly type="text" size="sm" value={this.state.status} />

React bootstrap form not rendering spaces in text inputs

I'm using react bootstrap components. I have form elements that follow this sort of structure:
class Example extends React.Component {
constructor (props) {
super(props)
this.state = {
name: '',
show: false
}
this.handleChange = this.handleChange.bind(this)
this.handleShow = this.handleShow.bind(this)
this.handleClose = this.handleClose.bind(this)
}
handleShow () {
this.setState({ show: true })
}
handleClose () {
this.setState({ show: false })
}
handleChange (e) {
this.setState({
[e.target.name]: e.target.value
})
}
render () {
return (
<div>
<Button bsStyle='success' onClick={this.handleShow}>Add New</Button>
<Modal show={this.state.show} onHide={this.handleClose}>
<Modal.Header closeButton>
<Modal.Title>Add New</Modal.Title>
</Modal.Header>
<Modal.Body>
<form>
<FormGroup>
<ControlLabel className='form-input'>1. Provide Name</ControlLabel>
<FormControl onChange={this.handleChange} className='form-input' type='text' placeholder='Name' name='name' value={this.state.name} />
</FormGroup>
</form>
</Modal.Body>
</Modal>
</div>
)
}
}
When I type in the text input it removes the spaces e.g. I type 'hello world' but it renders 'helloworld'
I can't seem to find an answer for this.
Edit: I forgot to mention the form is rendering within a bootstrap modal, I don't know if that's what's causing the issue? I've just refactored my code and updated my example snippet to match.
Problem solved: The issue solved itself when we separated the button out so the button was not part of the component and we just return the modal.
import React, { Component } from 'react';
import { render } from 'react-dom';
import { FormGroup, ControlLabel, FormControl } from 'react-bootstrap'
class App extends Component {
constructor (props) {
super(props)
this.state = {
name: ''
}
this.handleChange = this.handleChange.bind(this)
}
handleChange (e) {
this.setState({
[e.target.name]: e.target.value
})
}
render () {
return (
<form>
<FormGroup>
<ControlLabel className='form-input'>1. Provide Name</ControlLabel>
<FormControl onChange={this.handleChange} className='form-input' type='text' placeholder='Name' name='name' value={this.state.name} />
</FormGroup>
</form>
)
}
}
render(<App />, document.getElementById('root'));

Redux-form onSubmit nothing happens

I would like to ask, what I miss on my code. It seems submitForm function is not working/triggering when I submit the form. I can't get values from my form fields. Here's my code:
import React from 'react';
import { reduxForm,reset, Field } from 'redux-form';
class FormProfile extends React.Component {
submitForm(formProps){
console.log(formProps);
}
render(){
const { error, handleSubmit } = this.props;
return (
<form onSubmit={this.submitForm.bind(this)}>
<Row>
<Col lg={6}>
<Field name="name" type="text" component={TextBoxComponent} placeholder="Compay Name" label="* Company Name" required />
<Field name="website" type="text" component={TextBoxComponent} placeholder="www.yourdomain.com" label="Website" />
<Field name="email" type="text" component={TextBoxComponent} placeholder="How can we contact your Company" label="* Contact Email" required />
</Col>
</Row>
</form>
);
}
}
const form = reduxForm({
form: 'CreateCompanyProfileForm',
validate
});
function validate(formProps){
const error = {};
return error;
}
export default (form(FormProfile));
TextBox Componen
import React from "react";
class TextBoxComponent extends React.Component {
render(){
return (
<div className="form-group">
<label className="control-label">{this.props.label}</label>
{ this.props.sublabel !== undefined ?
<em className="text-info"> { this.props.sublabel }</em>
:null}
<input { ...this.props } type={this.props.type} placeholder={this.props.placeholder} className="form-control"/>
{ this.props.required && <span className="text-error"></span> }
</div>
);
}
}
export default TextBoxComponent;
You should modify this line:
<form onSubmit={this.submitForm.bind(this)}>
to:
<form onSubmit={handleSubmit}>
then you can remove:
submitForm(formProps){
console.log(formProps);
}
Then you can create a new component to wrap redux form component:
class SamplePage extends React.Component {
handleSubmit = (values) => {
// Do something with the form values
console.log(values);
}
render() {
return (
<FormProfile onSubmit={this.handleSubmit} />
);
}
}
Anyway, you should check the example from Redux-form docs: http://redux-form.com/6.5.0/docs/GettingStarted.md/

Resources