I am new to react,
I am using card, when card "on click" i need to get the card object and place it in form dynamically,
(full code)
My code:
// reactstrap components
import {useState} from "react"
import {
Card,
CardHeader,
CardBody,
CardTitle,
Col,
Input,
FormGroup,
Form,
Container,
Row,
UncontrolledDropdown,
DropdownToggle,
DropdownItem,
DropdownMenu,
Button,
} from "reactstrap";
import Header from "components/Headers/Header.js";
import 'react-toastify/dist/ReactToastify.css';
import Navbar from "components/Navbars/modulenavbar"
import axios from "axios";
import React from "react";
import { Link } from "react-router-dom";
var apitoken= localStorage.getItem('apitoken');
const api=axios.create({baseURL:"https://api/v1/account"})
const options = {
headers: {'Authorization': apitoken}
}
const Accounts = () => {
const [accounts, setaccount] = React.useState([]);
const [loading, setLoading] = React.useState(true);
const [disabled, setDisabled] = useState(false);
React.useEffect(async () => {
const response = await api.get("/",options);
setaccount(response.data.response);
setLoading(false);
}, []);
if (loading) {
return <>Loading...</>;
}
function handleGameClick() {
setDisabled(!disabled);
}
This is were i get all my api value and append it
return (
<>
{accounts.map((student, index) => {
const { id, name, phone, email } = student //destructuring
return (
<>
<div style={{ width: "18rem" }} onClick={() => console.log(student)}>
I want to pass the object "Student" and use it in the default value of the forms shown below
<Card className="card-stats mb-4 mb-lg-1">
<CardBody>
<Row>
<div className="col">
<CardTitle className="h4 font-weight-bold mb-0">
{name}
</CardTitle>
<span className="h5">{phone}</span>
</div>
<div className="col">
<span className="h5">{email}</span>
</div>
</Row>
</CardBody>
</Card>
</div>
</>
)
})}
</>
)
}
Form Shows here
const Display = () => {
return (
<>
<Header />
<Container className="mt--7" fluid>
{/* Table */}
<Row>
<Col className="order-xl-1 " xl="2">
<CardHeader className="bg-white border-0">
<Row className="align-items-center">
<Col xs="8">
<Link to="/admin//accounts" className="ni ni-bold-left">
<span> View Account</span></Link>
</Col>
</Row>
</CardHeader>
<Card className="bg-secondary shadow navbar-nav-scroll">
<Accounts/>
</Card>
</Col>
<Col className="order-xl-1" xl="10">
<Card className="bg-secondary shadow">
<Navbar/>
<Row >
<Col className="shadow navbar-nav-scroll">
<Form>
<h6 className="heading-small text-muted mb-4">
Account Information
</h6>
<div className="pl-lg-4">
<Row>
<Col >
<FormGroup>
<label
className="form-control-label"
htmlFor="input-username"
>
Account Name
</label>
<Input
className="form-control-alternative"
id="input-username"
placeholder="Username"
type="text"
defaultValue={student.value}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col >
<FormGroup>
<label
className="form-control-label"
htmlFor="input-email"
>
Email address
</label>
<Input
className="form-control-alternative"
id="input-email"
placeholder="jesse#example.com"
type="email"
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col >
<FormGroup>
<label
className="form-control-label"
htmlFor="input-email"
>
Phone
</label>
<Input
className="form-control-alternative"
id="input-phone"
placeholder="Phone"
type="text"
/>
</FormGroup>
</Col>
</Row>
</div>
</Form>
</Col>
<Col xs="9">
<Card className="card-stats mb-4 mb-lg-0">
<CardBody>
<div>
<Row className="align-items-center">
<Col xs="8">
</Col>
<Col className="text-right" xs="4">
<Button
color="success"
href="#pablo"
// onClick={save}
>
Save
</Button>
</Col>
</Row>
</div>
</CardBody>
</Card>
</Col>
</Row>
</Card>
</Col>
</Row>
</Container>
</>
);
};
export default Display;
Note:The above three sections of code is in the single component
I just want to dynamically append the values from object during "on click" event
Thanks in advance
You can store the clicked student value in state and pass it on to whichever component needs it as props
const Accounts = () => {
const [selectedStudent, setSelectedStudent] = useState({});
...
const handleStudentClick = (student) => {
setSelectedStudent(student)
}
return (
<>
{accounts.map((student, index) => {
const { id, name, phone, email } = student //destructuring
return (
<>
<div style={{ width: "18rem" }} onClick={() => handleStudentClick(student)}>
Now you can pass selected student as props to your child component
Related
I'm trying to use a spinbox in my code but whenever I try changing the values using onChange, the app crashes.
I also tried using onValueChange but it's getting ignored and I don't know what the problem is:
item.js
import NumericInput from "react-numeric-input";
import { Row, Col, ListGroup } from "react-bootstrap";
function ItemScreen() {
const [qty, setQty] = useState(1);
return (
<div>
<h2 className="text-center mb-3">Order</h2>
<hr></hr>
<Row>
<Col md={8}>
<ListGroup variant="flush">
<ListGroup.Item>
<Row>
<Col>Apple</Col>
<Col>
<NumericInput
min={1}
max={100}
onChange={(e) => setQty(e.target.value)}
value={qty}
/>
</Col>
<Col>
500 x {qty} = {qty * 500}
</Col>
</Row>
</ListGroup.Item>
</ListGroup>
</Col>
</Row>
</div>
);
}
export default ItemScreen;
the NumericInput component event just return the numeric value so you can this I guess :
<NumericInput
min={1}
max={100}
onChange={(value) => setQty(value)}
/>
The value will always be of type string.
So you need to cast it as a number.
onChange={(e) => setQty(Number(e.target.value))}
I'm trying to make a reusable input component. When data enters I want to handle those input data in the same place where I use that reusable input component. Not passing that as props.
I'm getting an error
Uncaught TypeError: Cannot read property 'value' of undefined
Can anyone give me any idea about how to handle data in such an instance?
InputFieldWithImage.js
import React, {useState} from "react";
import { Form, FormGroup, Input } from 'reactstrap';
function InputFieldWithImage(props) {
const [inputType] = useState(props.type)
const [inputValue, setInputValue] = useState('')
function handleChange(event){
console.log("Input.js");
console.log(inputValue);
setInputValue(event.target.value);
if(props.onChange) props.onChange(inputValue)
}
return (
<>
<Input type={inputType} value={inputValue} name="input-form" onChange={handleChange} class="inputclass"/>
</>
);
}
export default InputFieldWithImage;
AddTicket.js
import { Row, Col } from 'reactstrap';
import { Form, FormGroup, Input } from 'reactstrap';
import ActionButton from './../../components/ButtonComponent';
import InputFieldWithImage from './../../components/InputField/InputFieldWithImage'
import { render } from 'react-dom';
import ReactQuill from 'react-quill';
const AddTicket = (props) => {
const [assignee, setAssignee] = useState('');
const handleSubmit = (evt) => {
evt.preventDefault();
console.log('Assignee:' + assignee);
props.handleClose();
};
const test = () => {
console.log("text");
console.log('Assignee:' + assignee);
};
return (
<div className="popup-box">
<div className="box">
{/* <span className="close-icon" onClick={props.handleClose}>
x
</span> */}
<Form onSubmit={handleSubmit} style={{paddingLeft:30,paddingTop:50}}>
<Row style={{ paddingBottom: 50 }}>
<Col sm={11} xs={11} md={11}>
<h1>Add new ticket </h1>
</Col>
<Col onClick={props.handleClose} m={1} xs={1} md={1}>
<h1 className="close-icon">X </h1>
</Col>
</Row>
<FormGroup>
<Row style={{ marginBottom: '25px' }}>
<Col sm={2}>
<h4>Assignee</h4>
</Col>
<Col sm={2}>
<InputFieldWithImage value={assignee} onChange={(e) => setAssignee(e.target.value)} />
</Col>
</Row>
</FormGroup>
<Row>
<Col sm={2}></Col>
<Col>
<ActionButton text="Send" />
</Col>
</Row>
</Form>
</div>
</div>
);
};
export default AddTicket;
You need to pass event instead of inputValue . As there is input.target.value . That's why its giving error
function handleChange(event) {
console.log("Input.js");
console.log(inputValue);
setInputValue(event.target.value);
if (props.onChange) props.onChange(event);
}
Here is demo: https://codesandbox.io/s/hidden-tree-vr834?file=/src/App.js
The error only shows up when I visit login page in the application, however the register page looks fine.
The form in the login page is created with reactstrap. The application works fine in development mode, as soon as I created production build using yarn build the problem arose.
Following is my Login.js Component
import React, { Component } from 'react';
import { Button, Col, Container, Row, Form, FormGroup, Input, Label, Alert } from 'reactstrap';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { AuthContext } from '../contexts/AuthContext';
class Login extends Component {
static contextType = AuthContext;
state = {
isSubmitting: false,
failed: false
}
handleSubmit = e => {
e.preventDefault();
this.setState({
isSubmitting: true
});
const loginData = {
email: this.email,
password: this.password
}
axios.post('login', loginData)
.then( res => {
this.setState({
isSubmitting: false
});
if(res.status === 200){
const user = res.data.data;
const userData = {
id: user.id,
name: user.name,
api_token: user.api_token
}
if(user){
this.context.setUser(userData);
this.context.storeUser(userData);
this.context.setAuthenticated(true);
let pageToGo;
if(this.props.history.location.state !== undefined){
const pageFrom = this.props.history.location.state.page;
pageToGo = pageFrom ? pageFrom : '/dashboard';
this.props.history.push(pageToGo);
}else{
this.props.history.push('/dashboard');
}
}else{
this.setState({
failed: true
});
}
}else{
this.setState({
failed: true
});
}
} )
.catch( err => {
console.log(err);
})
}
handleLogout = () => {
this.context.logout();
this.props.history.push('/');
}
RenderErrorMessages = () => {
if(this.state.failed){
return(
<div>
<Alert color="danger">Invalid Credentials! Try again with correct credentials!</Alert>
</div>
)
}else{
return(
<div>
</div>
)
}
}
RenderDashboard = () => {
return(
<div>
<Container className="shadow-sm" style={{backgroundColor: '#fff'}}>
<Row className="p-5" color="white" >
<Col className="pb-4 border-bottom" md="12">
<h2 className="mb-3">Hi, {this.context.user.name}</h2>
<h5 className="font-weight-normal">You are logged in!</h5>
</Col>
</Row>
<Row className="pb-5 px-5">
<Col md="6">
<Col md="12">
<p>Do you want to go to your dashboard?</p>
<Button className="mr-2" tag={Link} to="/dashboard">Go to Dashboard</Button>
</Col>
<Col md="12" className="mt-4">
<p>Do you want to logout?</p>
<Button onClick={() => this.handleLogout()} >Log Out</Button>
</Col>
</Col>
</Row>
</Container>
</div>
)
}
RenderLoginForm = () => {
return (
<Container className="py-5" >
<Row className="justify-content-center">
<Col md="8">
<h3 className="pb-3 mb-2 text-uppercase font-weight-bold text-sm" style={{fontSize: '18px'}}>Login to start your session!</h3>
</Col>
</Row>
<Row className="justify-content-center">
<Col md="8">
<this.RenderErrorMessages />
</Col>
</Row>
<Row className="justify-content-center">
<Col className="p-5 shadow-sm" md="8" style={{backgroundColor: '#fff'}}>
<Form onSubmit={this.handleSubmit}>
<FormGroup>
<Label htmlFor="email" className="font-weight-bold">Email</Label>
<Input
type="email"
name="email"
placeholder="Enter Your Email"
onChange={e => this.email = e.target.value}
required={true}
/>
</FormGroup>
<FormGroup>
<Label htmlFor="password" className="font-weight-bold">Password</Label>
<Input
type="password"
name="password"
placeholder="Enter Your Password"
onChange={e => this.password = e.target.value}
required={true}
/>
</FormGroup>
<Button className="mt-4" type="submit" name="submit" disabled={this.state.isSubmitting}>{this.state.isSubmitting ? 'loading..' : 'Submit'}</Button>
<p className="text-right mt-2">Don't have an account? <Link to="/register">Sign Up Here</Link></p>
</Form>
</Col>
</Row>
</Container>
)
}
render() {
return(
<div className="py-5" style={{backgroundColor: '#f5f5f5'}}>
{this.context.authenticated ? <this.RenderDashboard /> : <this.RenderLoginForm />}
</div>
)
}
}
export default Login;
Here is the complete log of the error.
Error: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=undefined&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
I am working on a React project, In that I have a card, In the card I have react icon so what
I am trying to do is If I click the react icon, then file upload dialogue box has to open
please someone help to achieve this I am using Reactstrap for this
This is my code Form.js
import React, { useState, useRef } from 'react';
import './Form.css';
import { MdCloudUpload } from 'react-icons/md';
import { Row,Col,Button,Modal,ModalBody,ModalFooter } from 'reactstrap'
const Form = () => {
const inputFile = useRef(null)
const onButtonClick = () => {
inputFile.current.click();
};
return (
<Row>
<Col md="6" sm="6" xs="6">
<Modal isOpen={true}
>
<ModalBody>
<Row>
<Col md="4" sm="4" xs="4">
<div className="image-upload">
<input type='file' id='file' ref={inputFile} style={{ display: 'none' }}/>
<MdCloudUpload onClick={onButtonClick} className=' icon'></MdCloudUpload>
</div>
</Col>
<Col md="8" sm="8" xs="8">
</Col>
</Row>
</ModalBody>
<ModalFooter>
<Button color="secondary">
Cancel
</Button>
<Button type="submit" color="primary">
Submit
</Button>
</ModalFooter>
</Modal>
</Col>
</Row>
)
}
export default Form
there is two options:
use side library like react-dropzone
just add <input type="file" /> and trigger change event it when icon is clicked
here is an example
import React, { useState } from "react";
import "./Form.css";
import { MdCloudUpload } from "react-icons/md";
const Form = () => {
const onIconClick = () => {
const input = document.getElementById('file-input');
if (input) {
input.click();
}
};
return (
<Row>
<Col md="6" sm="6" xs="6">
<Modal isOpen={true}>
<ModalBody>
<Row>
<Col md="4" sm="4" xs="4">
<div className="image-upload">
<MdCloudUpload
className="icon"
onClick={onIconClick}
/>
<input
type="file"
id="file-input"
style={{ display: 'none' }}
/>
</div>
</Col>
<Col md="8" sm="8" xs="8" />
</Row>
</ModalBody>
<ModalFooter>
<Button color="secondary">Cancel</Button>
<Button type="submit" color="primary">
Submit
</Button>
</ModalFooter>
</Modal>
</Col>
</Row>
);
};
export default Form;
i am using react slick...and using class component, now i just want to convert class component to functional component....because in these component i need to use another function component...it getting some problem....could any one help on this thing...below the class i have used (renderArrows =) this i thing is getting problem...
this is the link of code sand box : https://codesandbox.io/s/jovial-smoke-ndzhj
import React, {Component } from 'react';
import { Col, Row } from 'react-grid-system';
import { ButtonBase } from '#material-ui/core';
import ArrowBackIosIcon from '#material-ui/icons/ArrowBackIos';
import ArrowForwardIosIcon from '#material-ui/icons/ArrowForwardIos';
import Slider from "react-slick";
class Example extends Component {
renderArrows = () => {
return (
<div className="slider-arrow">
<ButtonBase
className="arrow-btn prev"
onClick={() => this.slider.slickPrev()}
>
<ArrowBackIosIcon />
</ButtonBase>
<ButtonBase
className="arrow-btn next"
onClick={() => this.slider.slickNext()}
>
<ArrowForwardIosIcon />
</ButtonBase>
</div>
);
};
render() {
return (
<div>
<Col xl={12} lg={12} md={12} sm={12} xs={12} className="desktop-slider">
<div className="education-level main-boxes boxex-bottom">
<Row className="row">
<Col xl={4} lg={4} md={4} sm={12} xs={12}>
<div className="index-box-head horizontal-box-head">
1. Education Level
</div>
</Col>
<Col xl={8} lg={8} md={8} sm={12} xs={12}>
<div style={{ position: "relative" }}>
{this.renderArrows()}
<Slider
ref={c => (this.slider = c)}
dots={false}
arrows={false}
centerMode={true}
slidesToShow={1}
infinite={false}>
<li>Home
</li>
<li>About Us
</li>
<li>Gallery
</li>
</Slider>
</div>
</Col>
</Row>
</div>
</Col>
</div>
);
}
}
export default Example;
This can be the best answer
I tried and made this work with you sample
Check please
https://codesandbox.io/s/infallible-turing-wgvrb?file=/src/App.js
import React, { useRef } from "react";
import { Col, Row } from "react-grid-system";
import { ButtonBase } from "#material-ui/core";
import ArrowBackIosIcon from "#material-ui/icons/ArrowBackIos";
import ArrowForwardIosIcon from "#material-ui/icons/ArrowForwardIos";
import Slider from "react-slick";
const Example = () => {
const customSlider = useRef();
const renderArrows = () => {
return (
<div className="slider-arrow">
<ButtonBase
className="arrow-btn prev"
onClick={() => customSlider.current.slickPrev()}
>
<ArrowBackIosIcon />
</ButtonBase>
<ButtonBase
className="arrow-btn next"
onClick={() => customSlider.current.slickNext()}
>
<ArrowForwardIosIcon />
</ButtonBase>
</div>
);
};
return (
<div>
<Col xl={12} lg={12} md={12} sm={12} xs={12} className="desktop-slider">
<div className="education-level main-boxes boxex-bottom">
<Row className="row">
<Col xl={4} lg={4} md={4} sm={12} xs={12}>
<div className="index-box-head horizontal-box-head">
1. Education Level
</div>
</Col>
<Col xl={8} lg={8} md={8} sm={12} xs={12}>
<div style={{ position: "relative" }}>
{renderArrows()}
<Slider
ref={slider => (customSlider.current = slider)}
dots={false}
arrows={false}
centerMode={true}
slidesToShow={1}
infinite={false}
>
<li>Home</li>
<li>About Us</li>
<li>Gallery</li>
</Slider>
</div>
</Col>
</Row>
</div>
</Col>
</div>
);
};
export default Example;
class component to functional component:
import React, { Component } from 'react'
import { Col, Row } from 'react-grid-system'
import { ButtonBase } from '#material-ui/core'
import ArrowBackIosIcon from '#material-ui/icons/ArrowBackIos'
import ArrowForwardIosIcon from '#material-ui/icons/ArrowForwardIos'
import Slider from 'react-slick'
const renderArrows = () => {
return (
<div className="slider-arrow">
<ButtonBase
className="arrow-btn prev"
onClick={() => this.slider.slickPrev()}
>
<ArrowBackIosIcon />
</ButtonBase>
<ButtonBase
className="arrow-btn next"
onClick={() => this.slider.slickNext()}
>
<ArrowForwardIosIcon />
</ButtonBase>
</div>
)
}
const Example = () => {
return (
<div>
<Col xl={12} lg={12} md={12} sm={12} xs={12} className="desktop-slider">
<div className="education-level main-boxes boxex-bottom">
<Row className="row">
<Col xl={4} lg={4} md={4} sm={12} xs={12}>
<div className="index-box-head horizontal-box-head">
1. Education Level
</div>
</Col>
<Col xl={8} lg={8} md={8} sm={12} xs={12}>
<div style={{ position: 'relative' }}>
{renderArrows()}
<Slider
ref={c => (this.slider = c)}
dots={false}
arrows={false}
centerMode={true}
slidesToShow={1}
infinite={false}
>
<li>Home</li>
<li>About Us</li>
<li>Gallery</li>
</Slider>
</div>
</Col>
</Row>
</div>
</Col>
</div>
)
}
export default Example
One more thing, I don't seem to get from where this.slider.slickNext() came from. I think it would be this.Slider.slickPrev().
If I'm right, then for functional component, change it to Slider.slickPrev()