How can I access the value of my inputs in React? - reactjs

So I have a regular page, I am working with next js. It looks like this:
"use client"
import SubjectInput from "../../../../components/subjectsInput"
export default function Page()
{
let inputs = []
for (let i = 0; i < numberOfInputsGiven; i++) {
inputs.push(<SubjectInput key={i}/>)
}
return(
<>
<form>
<>
{inputs}
</>
<button type="submit">OK</button>
</form>
</>
)
}
I use a component called "SubjectInput", to generate the input fields I need. Now, my question is, how can I access the value of the inputs that are in SubjectInput? Here is what SubjectInput looks like:
export default function SubjectInput(){
return(
<div>
<div>
<label>Name</label>
<input type="text" placeholder="Enter subject's name" required />
</div>
<div>
<label>From</label>
<input type="time" placeholder="Enter subject's starting time" required />
</div>
<div>
<label>To</label>
<input type="time" placeholder="Enter subject's ending time" required />
</div>
</div>
)
}

I would create a component that just holds one label and input, import it into the main page and change the values through props.
Main page
import Input from "./components/Input";
function App() {
return (
<div className="App">
<form>
<Input label="my text" type="text" value="hello" />
<Input label="my number" type="number" value="123" />
<Input type="submit" />
</form>
</div>
);
}
export default App;
Input component
import React from "react";
const Input = (props) => {
return (
<div>
<label>{props.label}</label>
<input type={props.type} value={props.value} />
</div>
);
};
export default Input;

Related

Clicking on react button asks me to leave site

I am learning react and I have a component which as a 2 input fields and a button, at the moment, clicking on the button will display a message in console log, but when the button is clicked it displays a popup Leave site?, Changes that you made may not be saved.
this is my code in this component
import React, { useRef, useState, Component } from 'react'
import { useAuthState } from 'react-firebase-hooks/auth';
import { useCollectionData } from 'react-firebase-hooks/firestore';
import { signOut } from 'firebase/auth';
class InfoLgnTest extends Component {
render() {
this.state = {
user: null
}
return (
<div>
<div className="App">
<SignInWithEmailPassword />
</div>
</div>
)
}
}
function SignInWithEmailPassword() {
const emailRef = useRef()
const passwordRef = useRef()
const signIn = () => {
console.log("InfoLgnTest singin clicked")
}
return (
<>
<div className="form">
<form>
<div className="input-container">
<label>Username </label>
<input
name="email"
type="text"
ref={emailRef}
required
placeholder ="something#gmail.com"
/>
</div>
<div className="input-container">
<label>Password </label>
<input
type="text"
name="pass"
ref={passwordRef}
required
placeholder ="..."
/>
</div>
<div className="button-container">
<input type="submit" onClick={signIn}/>
</div>
</form>
</div>
</>
)
}
export default InfoLgnTest
This code has a form, by default form send data as a request on the same page, for resolve this:
Add onSubmit to form,
call preventDefault method from event
call the function signIn
Change <input type="submit" ... /> to <button type="submit">Send</button>
function SignInWithEmailPassword() {
const emailRef = useRef()
const passwordRef = useRef()
const signIn = () => {
console.log("InfoLgnTest singin clicked")
}
// new function to handle submit
const submitForm = (event) => {
event.preventDefault();
signIn();
}
return (
<>
<div className="form">
{/* Add onSubmit */}
<form onSubmit={submitForm}>
<div className="input-container">
<label>Username </label>
<input
name="email"
type="text"
ref={emailRef}
required
placeholder ="something#gmail.com"
/>
</div>
<div className="input-container">
<label>Password </label>
<input
type="text"
name="pass"
ref={passwordRef}
required
placeholder ="..."
/>
</div>
<div className="button-container">
{/* Change input to button */}
<button type="submit">Send</button>
</div>
</form>
</div>
</>
)
}

How do I add more number of rows at a time?

I am trying to build a table-like structure in which I want to add rows dynamically. Here is my code:
import { React, useState } from 'react';
function Table() {
const [add, setAdd] = useState(false);
return (
<div>
<div className="headings">
<p>Item Description</p>
<p>Quantity</p>
<p>Rate</p>
<p>Amount</p>
</div>
<div className="rows">
<input placeholder="Item Description" type="text" />
<input placeholder="Quantity" type="number" />
<input placeholder="Price per piece" type="number" />
<input placeholder="Amount" type="number" />
</div>
{
add ?
<div className="rows" >
<input placeholder="Item Description" type="text" />
<input placeholder="Quantity" type="number" />
<input placeholder="Price per piece" type="number" />
<input placeholder="Amount" type="number" />
</div>
:
<div></div>
}
<button className="add" onClick={()=>setAdd(true)}>Add another line item</button>
</div>
)
}
export default Table;
I have tried adding rows using the button but I am able to add only a single row. The state changes to true so can I reset the state or should I use any other method for adding rows?
You need to set a counter in order to track how many rows you have, and preferably pass it on to another component.
This is not a complete example, neither beautiful one, but the essence is there:
import { React, useState } from "react";
function Rows({ numberOfRows }) {
return [...Array(numberOfRows)].map((element, index) => (
<div key={index}>{`Row Number ${index}`}</div>
));
}
function Table() {
const [numberOfRows, setNumberOfRows] = useState(0);
const addRow = () => {
setNumberOfRows((prev) => prev + 1);
};
const deleteRow = () => {
if (numberOfRows > 0) {
setNumberOfRows((prev) => prev - 1);
}
};
return (
<div>
<div className="headings">
<p>Item Description</p>
<p>Quantity</p>
<p>Rate</p>
<p>Amount</p>
</div>
<Rows numberOfRows={numberOfRows} />
<button className="add" onClick={addRow}>
Add row
</button>
<button className="delete" onClick={deleteRow}>
Delete row
</button>
</div>
);
}
export default Table;
You could keep the lines in state:
import { React, useState } from 'react';
function Table() {
const [addedLines, setAddedLines] = useState([<div key={1} className="rows">
<input placeholder="Item Description" type="text" />
<input placeholder="Quantity" type="number" />
<input placeholder="Price per piece" type="number" />
<input placeholder="Amount" type="number" />
</div>]);
const addLine = () => {
const newLine = (<div key={ addedLines.length + 1 } className="rows" >
<input placeholder="Item Description" type="text" />
<input placeholder="Quantity" type="number" />
<input placeholder="Price per piece" type="number" />
<input placeholder="Amount" type="number" />
</div>)
let a = []
addedLines.forEach((x)=>a.push(x))
a.push(newLine)
setAddedLines(a)
}
return (
<div>
<div className="headings">
<p>Item Description</p>
<p>Quantity</p>
<p>Rate</p>
<p>Amount</p>
</div>
{ addedLines}
<button className="add" onClick={addLine}>Add another line item</button>
</div>
)
}
export default Table;
Codepen: https://codepen.io/guilhermebl/pen/vYxvBWE

React on button click Add textarea

I'm making a simple resume portal and I have a textarea(1), in which user can write his/her work experience. To add more than one work experience I have set a button(Add) which basically will add a new textarea(similar to textarea(1) but without label) just below the textarea(1) and so on. This all should be done when button(Add) is clicked.
If I am able to add my code in a child component that would solve my problem I think.
Here's below what I tried:
Child component ( src -> Routes -> UserForm -> Components -> UserDetails -> index.js )
import React from 'react'
import './style.scss';
import { Row, Col } from 'react-bootstrap'
const UserDetails = () => {
return (
<>
<div className='UserDetails'>
<Row>
<Col lg='6'>
<div className='persnlInfo'>
<h4>
Personal Information
</h4>
<p>Your Name</p>
<input type="text" placeholder="Enter here" />
<p>Your Contact</p>
<input type="text" placeholder="Enter here" />
<p>Your Address</p>
<textarea className='formAddress' rows="5" cols="10" placeholder="Enter here" />
<p id='impLinks'>Important Links</p>
<p>Facebook</p>
<input type="text" placeholder="Enter here" />
<p>Instagram</p>
<input type="text" placeholder="Enter here" />
<p>Linkedin</p>
<input type="text" placeholder="Enter here" />
</div>
</Col>
<Col lg='6'>
<h4>
Professional Information
</h4>
<p>Objective</p>
<textarea className='formObjective' rows="5" cols="10" placeholder="Enter here" />
<p>Work Experience</p>
<textarea className='formObjective' rows="3" cols="10" placeholder="Enter here" />
<div className='addButton'>
<input type='button' id='addWrkExp' value='Add' />
</div>
</Col>
</Row>
</div>
</>
)
}
export default UserDetails;
Parent component ( src -> Routes -> UserForm -> index.js )
import React from 'react'
import Pages from '../../Components/HOC/Page/index'
import UserDetails from '../UserForm/Components/UserDetails/index'
class UserForm extends React.Component{
render() {
return(
<>
<Pages
showHeader
showFooter
>
<UserDetails />
</Pages>
</>
);
}
}
export default UserForm;
Output:
To obtain the said above, I've searched up on this but not getting What and Where to put logic/code exactly. If I'm not wrong this can be done using state , props , onClick() and/or something related.
I hope this is enough from my side to understand the problem. Thanks in advance for your help.
You can use a useState for the number of textareas on your page and then when button(add) gets clicked, that state gets increased by one,
This is your Child component ( src -> Routes -> UserForm -> Components -> UserDetails -> index.js )
import React, { useState } from 'react'
import './style.scss';
import { Row, Col } from 'react-bootstrap'
const UserDetails = () => {
const [ workXPs, setWorkXPs ] = useState(1);
return (
<>
<div className='UserDetails'>
<Row>
<Col lg='6'>
<div className='persnlInfo'>
<h4>
Personal Information
</h4>
<p>Your Name</p>
<input type="text" placeholder="Enter here" />
<p>Your Contact</p>
<input type="text" placeholder="Enter here" />
<p>Your Address</p>
<textarea className='formAddress' rows="5" cols="10" placeholder="Enter here" />
<p id='impLinks'>Important Links</p>
<p>Facebook</p>
<input type="text" placeholder="Enter here" />
<p>Instagram</p>
<input type="text" placeholder="Enter here" />
<p>Linkedin</p>
<input type="text" placeholder="Enter here" />
</div>
</Col>
<Col lg='6'>
<h4>
Professional Information
</h4>
<p>Objective</p>
<textarea className='formObjective' rows="5" cols="10" placeholder="Enter here" />
<p>Work Experience</p>
{[...Array(workXPs).keys()].map((workXP, i) => {
return <textarea key={i} className='formObjective' rows="3" cols="10" placeholder="Enter here" />;
})}
<div className='addButton'>
<input type='button' id='addWrkExp' value='Add' onClick={() => setWorkXPs(prev => (prev + 1))} />
</div>
</Col>
</Row>
</div>
</>
)
}
export default UserDetails;
if you wanna do more advanced and add remove buttons, check this: https://www.educative.io/blog/react-hooks-tutorial-todo-list
hope this helps 🙂
You could just make a state and change the state on the button click.
Then change the style according to the state.
Parent Component
import React from "react";
import Pages from "../../Components/HOC/Page/index";
import UserDetails from "../UserForm/Components/UserDetails/index";
class UserForm extends React.Component {
state = {
textAreas: [{ text: "" }]
};
addTextArea = () => {
let updatedTextArea = [...this.state.textAreas];
updatedTextArea.push({ text: "" });
this.setState({ textAreas: updatedTextArea });
};
render() {
return (
<>
<Pages showHeader showFooter>
<UserDetails textAreas={this.state.textAreas} clicked={this.addTextArea} />
</Pages>
</>
);
}
}
export default UserForm;
i changed <UserDetails textAreas={textAreas} clicked={this.addTextArea} /> to <UserDetails textAreas={this.state.textAreas} clicked={this.addTextArea} />
in the UserForm component
child Component
import React from 'react'
import './style.scss';
import { Row, Col } from 'react-bootstrap'
const UserDetails = (props) => {
const {textAreas, clicked} = props
return (
<>
<div className='UserDetails'>
<Row>
<Col lg='6'>
<div className='persnlInfo'>
<h4>
Personal Information
</h4>
<p>Your Name</p>
<input type="text" placeholder="Enter here" />
<p>Your Contact</p>
<input type="text" placeholder="Enter here" />
<p>Your Address</p>
<textarea className='formAddress' rows="5" cols="10" placeholder="Enter here" />
<p id='impLinks'>Important Links</p>
<p>Facebook</p>
<input type="text" placeholder="Enter here" />
<p>Instagram</p>
<input type="text" placeholder="Enter here" />
<p>Linkedin</p>
<input type="text" placeholder="Enter here" />
</div>
</Col>
<Col lg='6'>
<h4>
Professional Information
</h4>
<p>Objective</p>
<textarea className='formObjective' rows="5"
cols="10" placeholder="Enter here" />
<p>Work Experience</p>
{textAreas.map(item => (
<textarea className='formObjective' value=
{item.value} rows="3" cols="10" placeholder="Enter
here" />
)) }
<div className='addButton' onClick={clicked}>
<input type='button' id='addWrkExp' value='Add' />
</div>
</Col>
</Row>
</div>
</>
)
}
export default UserDetails;

Inputting an ARRAY into a FORM field in REACT

I am trying to learn to code by following an eCommerce product tutorial guide in React.
I have finished setting up the product page and checkout.
My goal now is to extract the cart: [] along with the checkout total into a form using EmailJS.
import React from 'react';
import emailjs from 'emailjs-com';
import './form.css';
import { ProductConsumer } from '../../context'
import CartList from './CartList'
import CartColumns from "./CartColumns"
import CartTotals from './CartTotals'
import Title from "../Title";
import { ProductProvider } from "../../context"
import CartItem from './CartItem'
export default function CheckOut() {
function sendEmail(e) {
alert("Your order has been placed!")
e.preventDefault();
emailjs.sendForm('gmail', 'template_3DAGPnwJ', e.target, 'user_m49ol85bvoqFluF8IKatG')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
}
let Order = "cat"
return (
<div>
<ProductConsumer>
{value => {
return(
<div>
<Title name="Check" title="Out"/>
<CartColumns />
<CartList value={value} />
<CartTotals value={value}/>
</div>
)
}
}
</ProductConsumer>
<form className="contact-form" onSubmit={sendEmail}>
<label>Contact Number eg. 12345678 </label>
<input type="tel" name="contact_number" placeholder="12345678" pattern="[0-9]{8}" required />
<label>Name</label>
<input type="name" name="user_name" required />
<label>Email</label>
<input type="email" name="user_email" required />
<label>Address Line 1</label>
<input type="address-line1" name="user_address1" required />
<label>Address Line 2</label>
<input type="address-line2" name="user_address2" />
<label>Message (eg. Special Requests)</label>
<textarea name="message_html" />
<input type="submit" value="Place Order" />
<textarea name="proudct order" value={Order}/>
</form>
</div>
);
}
So far the textarea is showing "cat" from the let Order = "cat".
I would like to put the array information from CartList and CartTotal into Order. Once the client submits the form, I will have their name email address and the order they collected in the cart. This will be emailed to me via EmailJS.
import React from 'react';
import emailjs from 'emailjs-com';
import './form.css';
import { ProductConsumer } from '../../context';
import CartList from './CartList';
import CartTotals from './CartTotals';
import Title from '../Title';
export default function CheckOut() {
function sendEmail(e) {
alert('Your order has been placed! Our staff will get in touch with you to confirm your order and to process payment.');
e.preventDefault();
emailjs
.sendForm(
'gmail',
'xxxxxxxxx',
e.target,
'xxxxxxxxx'
)
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
}
const Form = ({ context }) => {
let Order = context.cart.map((item) => `ID: ${item.id} \n${item.title} \t $ ${item.price} \t Qty:${item.count} \n\n`);
let OrderSubtotal = context.cartSubtotal ;
let OrderServce = context.cartService;
let OrderShipping = context.cartShipping;
let OrderTotal = context.cartTotal;
return (
<form className="contact-form" onSubmit={sendEmail}>
<label>Contact Number eg. 12345678 </label>
<input
type="tel"
name="contact_number"
placeholder="12345678"
pattern="[0-9]{8}"
required
/>
<label>Name</label>
<input type="name" name="user_name" required />
<label>Email</label>
<input type="email" name="user_email" required />
<label>Address Line 1</label>
<input type="address-line1" name="user_address1" required />
<label>Address Line 2</label>
<input type="address-line2" name="user_address2" />
<label>Message (eg. Special Requests)</label>
<textarea name="message_html" />
<input type="submit" value="Place Order" />
<textarea style={{display:"none"}} name="Order" defaultValue={Order} />
<textarea style={{display:"none"}} name="OrderSubtotal" defaultValue={OrderSubtotal} />
<textarea style={{display:"none"}} name="OrderServce" defaultValue={OrderServce} />
<textarea style={{display:"none"}} name="OrderShipping" defaultValue={OrderShipping} />
<textarea style={{display:"none"}} name="OrderTotal" defaultValue={OrderTotal} />
</form>
);
};
return (
<div>
<ProductConsumer>
{(value) => {
return (
<div>
<Title name="Check" title="Out" />
<CartList value={value} />
<CartTotals value={value} />
</div>
);
}}
</ProductConsumer>
<ProductConsumer>
{(context) => <Form context={context} />}
</ProductConsumer>
</div>
);
}
The answer.
import { ProductConsumer } from '../../context';
let Order = context.cart.map((item) => ID: ${item.id} \n${item.title} \t $ ${item.price} \t Qty:${item.count} \n\n);
which is then exported to emailJS in the textarea.
<textarea style={{display:"none"}} name="Order" defaultValue={Order} />
and rendered
<ProductConsumer>
{(context) => <Form context={context} />}
</ProductConsumer>
Answer suggested by Metafield on Scrimba Discord Community. Thanks a ton!
You can and should use state to update any variable in a React component! CheckOut is a functional component. To use state in a functional component you have to use a hook, which is useState.
To get value from CartList and CartTotal and update Order, pass callback functions from CheckOut component.
Please check the following code, hope it helps.
import React, { useState } from "react";
import emailjs from "emailjs-com";
import "./form.css";
import { ProductConsumer } from "../../context";
import CartList from "./CartList";
import CartColumns from "./CartColumns";
import CartTotals from "./CartTotals";
import Title from "../Title";
import { ProductProvider } from "../../context";
import CartItem from "./CartItem";
export default function CheckOut() {
// Order default value is empty array. i.e. no orders
// updateOrder will update Order
const [Order, updateOrder] = useState([]);
// cartTotal to store CartTotals value
// updateCartTotal will update cartTotal
const [cartTotal, updateCartTotal] = useState(0);
function sendEmail(e) {
alert("Your order has been placed!");
e.preventDefault();
// You can access Order and cartTotal here.
console.log(Order, cartTotal);
emailjs
.sendForm(
"gmail",
"template_3DAGPnwJ",
e.target,
"user_m49ol85bvoqFluF8IKatG"
)
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
}
return (
<div>
<ProductConsumer>
{(value) => {
return (
<div>
<Title name="Check" title="Out" />
<CartColumns />
{/* updateOrder is a callback passed by prop */}
<CartList value={value} onCartUpdate={updateOrder} />
{/* updateCartTotal is a callback passed by prop */}
<CartTotals value={value} onCartTotalUpdate={updateCartTotal} />
</div>
);
}}
</ProductConsumer>
<form className="contact-form" onSubmit={sendEmail}>
<label>Contact Number eg. 12345678 </label>
<input
type="tel"
name="contact_number"
placeholder="12345678"
pattern="[0-9]{8}"
required
/>
<label>Name</label>
<input type="name" name="user_name" required />
<label>Email</label>
<input type="email" name="user_email" required />
<label>Address Line 1</label>
<input type="address-line1" name="user_address1" required />
<label>Address Line 2</label>
<input type="address-line2" name="user_address2" />
<label>Message (eg. Special Requests)</label>
<textarea name="message_html" />
<input type="submit" value="Place Order" />
<textarea name="proudct order" value={Order} />
</form>
</div>
);
}
I see your input fields are uncontrolled! React suggests to use a controlled component for form input. You can get idea from here - https://reactjs.org/docs/forms.html#controlled-components
Also, since you are learning React I suggest you read about two core parts of React. They are props and state.
For working with forms you can check this popular form handling library for react. https://formik.org/

How get values from a select/option field in redux-form?

I am trying to get the values from my second form. It renders some select options and when I hit the delete button it just returns an empty object. How do I get the value from the options. With the normal input fields it would pass values with the name.
For example if I had an input type="text" name="email", when I would submit this it would give my an object like:
{email: "some string"}
Here is the code:
import React , { Component } from 'react';
// import * as actions from '../actions';
import { reduxForm, Field } from 'redux-form';
import {connect} from 'react-redux';
import {postBooks, deleteBook} from '../../actions/booksActions';
class BooksForm extends Component {
renderField(field) {
const { meta: {touched, error} } = field;
const className = `form-group ${touched && error ? 'has-danger' : ''}`;
return (
<div className={className}>
<label className="control-label"><strong>{field.label}:</strong></label>
<input
className="form-control"
type={field.type}
{...field.input}
/>
<div className="text-help">
{ touched ? error : ''}
</div>
</div>
);
}
renderSelectField(field) {
const bookList = _.map(field.options, (book) => {
return (
<option key={book._id}>{book.title}</option>
)
});
return(
<div className="form-group">
<label htmlFor="sel1" className="control-label">{field.label}</label>
<select className="form-control" id="sel1">
{bookList}
</select>
</div>
);
}
onSubmit(values) {
this.props.postBooks(values);
}
onDelete(values) {
console.log(values);
}
render() {
const {handleSubmit} = this.props;
return (
<div>
<div className="well">
<form className="panel" onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<div className="panel-body">
<Field
label="Title"
name="title"
type="text"
component={this.renderField}
/>
<Field
label="Description"
name="description"
type="text"
component={this.renderField}
/>
<Field
label="Price"
name="price"
type="text"
component={this.renderField}
/>
<button className="btn btn-primary">Save Book</button>
</div>
</form>
</div>
<form className="Panel" onSubmit={handleSubmit(this.onDelete.bind(this))}>
<div className="panel-body">
<Field
label="Select Book"
name="selectedBook"
options={this.props.books}
component={this.renderSelectField}
/>
<button className="btn btn-danger">Delete</button>
</div>
</form>
</div>
);
}
}
function validate(values) {
const errors = {};
return errors;
}
function mapStateToProps(state) {
return {
books: state.books
}
}
export default reduxForm({
validate,
form: 'bookForm'
})(connect(mapStateToProps, {postBooks, deleteBook})(BooksForm));
In renderSelectField I needed to add {...field.input} into the select to allow redux-form to monitor it.
<select className="form-control" id="sel1" {...field.input}>

Resources