How to hide a Button, Only if Value is there in Input tag in React - reactjs

I am working on a React project, In my project I have one button If I click that button one
model is appearing. In that Model I have two Input tags and three buttons.
Here comes the login, In UI If Input tags have a Value then I have to hide Blue button in UI.
And If In UI If Input tags have no Value then I have to hide Red Buuton in UI this time I have
to show Blue button.
This is App.js
import React, { useState } from 'react';
import './App.css';
import Form from './Form/Form';
function App() {
const [show, setShow] = useState(false)
return (
<div className="App">
<button className='btn btn-danger'
onClick={() => setShow(true)}>Click here</button>
{ show && <Form></Form>}
</div>
);
}
export default App;
This is Form.js
import React, { useState } from 'react';
import './Form.css';
import {
Row,
Col,
Button,
ButtonGroup,
Card,
CardHeader,
CardSubtitle,
CardBody,
CardText,
Container,
Modal,
ModalBody,
ModalFooter,
ModalHeader,
FormGroup,
Label,
Input,
UncontrolledButtonDropdown,
DropdownToggle,
DropdownMenu,
DropdownItem
} from 'reactstrap';
const Form = () => {
const fun = () => {
}
return (
<div>
<Row>
<Col md="6" sm="6" xs="6">
<Modal
isOpen>
<ModalHeader >Add Role</ModalHeader>
<ModalBody>
<FormGroup>
<Label for="exampleName">Name</Label>
<Input
type="text"
name="name"
placeholder="Enter Your Name"
value='Tom'
/>
</FormGroup>
<FormGroup>
<Label for="exampleEmail">Description</Label>
<Input
type="textarea"
name="description"
placeholder="Enter Description"
value='React developer'
/>
</FormGroup>
</ModalBody>
<ModalFooter>
<Button color="secondary">
Cancel
</Button>
<Button className='one' color="primary">
Blue
</Button>
<Button color='danger'>Red</Button>
</ModalFooter>
</Modal>
</Col>
</Row>
</div>
)
}
export default Form
If you feel I am not clear with my doubt please put a comment.

you can check truthy value. If input has value, show 1 button and hide the other
const Form = () => {
const [value1, setValue1] = useState('');
const [value2, setValue2] = useState('');
return (
<div>
<Input
type="text"
name="name"
placeholder="Enter Your Name"
value={value1}
onChange={e => setValue1(e.target.value)}
/>
<Input
type="text"
name="value2"
placeholder="Enter Your Email"
value={value2}
onChange={e => setValue2(e.target.value)}
/>
{(!value1 || !value2) && <Button>Blue</Button>} // Show button if there is some value
{(value1 && value2) && <Button>Rad</Button>} // Show button if field is empty
</div>
);
}

Related

Check React useState() with console.log doesn't work properly

I'm trying to get data from 2 text boxes using react useState. But when I check the console.log, it takes text letters one by one as an array.
create.js
import React, {useState} from 'react'
import { Form, Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
export default function Create() {
const[firstName, setFirstName] = useState('');
const[lastName, setLasttName] = useState('');
console.log(firstName);
console.log(lastName);
return (
<div>
<div>create</div>
<div>
<Form>
<Form.Group className="mb-3" >
<Form.Label>First Name</Form.Label>
<Form.Control type="text" name='fName'
onChange={(e)=> setFirstName(e.target.value)}
placeholder="Enter first name" />
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Last Name</Form.Label>
<Form.Control type="text" name='lName'
onChange={(e)=> setLasttName(e.target.value)}
placeholder="Enter last name" />
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</div>
</div>
)
}
App.js
import './App.css';
import Create from './Components/create';
function App() {
return (
<div className="App">
<h2>Hello</h2>
<Create/>
</div>
);
}
export default App;
This is how the console looks like.
Console should be as shown below
The onChange function gets triggered every time the input changes. If you want it to trigger only once, when you are done typing, you can use onBlur this will assign the values only when the input field gets blurred.
Here's a sandbox for you to play with. Make sure you check the console to see when firstName gets updated https://codesandbox.io/s/pedantic-tharp-rfnxqg?file=/src/App.js
I would highly suggest that you check out React Hook Forms
import React, {useState} from 'react'
import { Form, Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
export default function Create() {
const[firstName, setFirstName] = useState('');
const[lastName, setLasttName] = useState('');
const submitForm =(e)=>{
console.log(firstName)
console.log(lastName)
e.preventDefault()
}
return (
<div>
<div>create</div>
<div>
<Form onSubmit={(e)=>submitForm(e)}>
<Form.Group className="mb-3" >
<Form.Label>First Name</Form.Label>
<Form.Control type="text" name='fName'
onChange={(e)=> setFirstName(e.target.value)}
placeholder="Enter first name" />
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Last Name</Form.Label>
<Form.Control type="text" name='lName'
onChange={(e)=> setLasttName(e.target.value)}
placeholder="Enter last name" />
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</div>
</div>
)
}

How can we be able to generate another element by clicking on a button?

How can we be able to generate another element by clicking on a button? in my case I want to add another input when I click on the button.
import React from 'react';
function App() {
return (
<Form>
<Form.Group controlId="formBasicEmail">
<Form.Control type="email" placeholder="Enter email" />
</Form.Group>
<Button variant="primary">Add another input</Button>
</Form>
);
}
export default App;
import React, { useState} from 'react';
function App() {
const [activeInput, setActiveInput] = useState(false)
const handleClick = () => {
setActiveInput(!activeInput)
}
return (
<Form>
<Form.Group controlId="formBasicEmail">
<Form.Control type="email" placeholder="Enter email" />
</Form.Group>
{ activeInput && <input type="text" placeholder="type something "/> }
<Button variant="primary"
onClick={handleClick}
>Add another input</Button>
</Form>
);
}
export default App;

react js + reactstrap + bootstrap-select

I'm trying to use the react + bootstrap + bootstrap-select. I've successfully changed the select dropdown to bootstrap-select but the click event's aren't getting triggered.
import React, { useEffect, useRef, createRef,forwardRef } from 'react';
import { Modal, ModalHeader, ModalBody, ModalFooter, Col, Row, Button, Form, FormGroup, Label, Input } from 'reactstrap';
import $ from 'jquery';
import 'bootstrap-select/dist/js/bootstrap-select.min.js';
import 'bootstrap-select/dist/css/bootstrap-select.min.css';
const AddPModal = ({ addPModalShow, hideModal }) => {
const handleSelectPicker = ()=>{
console.log($('#add_tag').selectpicker());
}
return (
<Modal size="lg" isOpen={addPModalShow} centered={true} onOpened={handleSelectPicker}>
<ModalHeader>Add New Prospect</ModalHeader>
<ModalBody>
<Form>
<Row form>
<Col md={6}>
<FormGroup>
<Label for="add_tag">tag</Label>
<select name="tag" id="add_tag" className="form-control">
<option>1</option>
<option>2</option><option>3</option>
</select>
</FormGroup>
</Col>
</Row>
</Form>
</ModalBody>
<ModalFooter>
<Button color="primary">Save</Button>
<Button color="secondary" onClick={hideModal}>Cancel</Button>
</ModalFooter>
</Modal>
);
}
export default AddPModal;
...
<select name="tag" id="add_tag" className="form-control selectpicker">
<option>1</option>
<option>2</option><option>3</option>
</select>
...
Add selectpicker class to your select elements to auto-initialize bootstrap-select.
For more info click here
Even you can use:
useEffect(() => {
$("#mySelect").selectpicker("refresh");
}, []);
To initialize your selectpicker element (it will render properly) - it will not work as the jquery event handlers are not called (required for all functionality.
Best is to avoid jquery in your react project.

How to show default value in console in react?

I am working on a React project, In that Project I have a form, In that form I have two Input
Tags. For first input tag I defined the value, For the second input tag I am assigning value by
using state. Now I am trying to console values of two Input tags but I am getting only second
Input tag value. So someone please help me to get Two Input tag values from form
This is Form.js
import React, { useState } from 'react';
import './aum-company-modal.css';
import Aumservice from '../../service/aum-service';
import { Button, Col, Modal, ModalBody,ModalFooter, ModalHeader, Row, FormGroup, Label, Input, } from 'reactstrap';
const AumCompanyModal = (props) => {
const [data, sendData] = useState({})
const [firstInputValue] = useState('1000')
const [inputValue, setInputValue] = useState('');
const handleChange = ({target}) => {
const { name, value } = target;
console.warn(name,value)
const newData = Object.assign({}, data, { [name]: value })
sendData(newData)
if (value > -1 && value < 100000000000000000000000000000000000) {
setInputValue(value);
}
}
const handleSubmit = (e) => {
e.preventDefault()
console.log(data)
}
return (
<Row>
<Col md="6" sm="6" xs="6">
<Modal isOpen={props.openModal}
>
<ModalHeader >Add new</ModalHeader>
<ModalBody>
<Row>
<Col md="12" sm="12" xs="12">
<FormGroup>
<Label for="exampleName">Min Value</Label>
<Input
type="text"
name="minValue"
placeholder="Enter minimum value"
value={firstInputValue}
/>
</FormGroup>
<FormGroup>
<Label for="exampleName">Max Value</Label>
<Input
type="number"
name="maxValue"
placeholder="Enter maximum value"
min='1000' max='100000000000000000000000000000000000'
value={inputValue}
onChange={handleChange}
/>
</FormGroup>
</Col>
</Row>
</ModalBody>
<ModalFooter>
<Button color="secondary" onClick={props.closeModal}>
Cancel
</Button>
<Button type="submit" onClick={handleSubmit} color="primary">
Submit
</Button>
</ModalFooter>
</Modal>
</Col>
</Row>
)
}
export default AumCompanyModal
If you have any doubt please put a comment.
If for some reason, you need to hard code some value, use state variable as value and then you will have that variable in handleSubmit. Or you can use ref and get value from that ref
const [firstValue] = useState('100');
<Input
type="text"
name="minValue"
placeholder="Enter minimum value"
value={firstValue}
/>
Or you can use React.useRef()
const firstInput = React.useRef();
<Input
type="text"
name="minValue"
placeholder="Enter minimum value"
value="1000"
ref={firstInput}
/>
// in handleSubmit
const handleSubmit = (e) => {
e.preventDefault()
console.log(firstInput.current.value)
}

How to handle submitted values in my form using redux-form and serverside validation?

I'm using redux-form with a login form component in ReactJS.
But when I pass values to my form and I click on the submit button the values returned by the console.log are empty, and I don't know how to debug that.
Here's my form component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link, withRouter } from 'react-router-dom';
import {reduxForm, Field} from 'redux-form';
import classnames from 'classnames'
// Actions
import {signin} from '../../actions/auth';
// Bootstrap
import { Grid, Row, Col, Image } from 'react-bootstrap';
// Includes
import '../../assets/css/users/signin.min.css';
import logo from '../../assets/images/datazonia_icone.png';
const renderField = ({input, label, type, forgotPassword=false, meta: {touched, error}}) =>(
<div className="form-group">
<label>{label}</label>
<input {...input} type={type}/>
{forgotPassword &&
<span className="forgot-pw">
<Link to="/users/password/reset">mot de passe oubliƩ ?</Link>
</span>}
{touched &&
error &&
<span className="help-block">
{error}
</span>}
</div>);
let SigninForm = (props) => {
const {handleSubmit, submitting, error } = props;
return (
<form onSubmit={handleSubmit}>
<Field
name="login"
component={renderField}
type='text'
input={{
className: "form-control"
}}
label="Email ou nom d'utilisateur"
/>
<Field
name="password"
component={renderField}
type="password"
input={{
className: "form-control"
}}
label='Mot de passe'
forgotPassword
/>
{error &&
<strong>
{error}
</strong>}
<button disabled={submitting} type="submit" className="btn btn-block btn-datazonia">Connexion</button>
</form>
);
};
SigninForm = reduxForm({
form: 'signin'
})(SigninForm);
class UserSignin extends Component {
onSubmit = (values) => {
console.log(values);
return this.props.signin(values, this.props.history, 'users');
};
render() {
return (
<div className="UserSignin">
<Grid>
<Row className="show-grid bloc-sign">
<Col sm={4} smOffset={4} xs={12} className="text-center title">
<Link to="/">
<Image src={logo} responsive className="center-block"/>
</Link>
<h3>Se connecter</h3>
</Col>
<Col sm={4} smOffset={4} xs={12}>
<div className="signin-form">
<SigninForm onSubmit={this.onSubmit}/>
</div>
</Col>
</Row>
</Grid>
</div>
);
}
}
UserSignin = connect(null, {signin})(withRouter(UserSignin));
export default UserSignin;
My values are empty when i click on the submit button, how can i get it to work ?
(And sorry for my English, I'm French)
OK, I've resolved this issue.
the problem was
input={{
className: "form-control"
}}
overrides the default behavior of redux-form

Resources