EmailJs and Form validation control - reactjs

How do I add the verification of my fields!
I'm trying to send emails like this [emailjs][1], but I realise that I can also submit my empty form! So I'm wondering how to adjust my code so that it takes into account the verification of fields!
I have followed the documentation on emailjs about submitting a form with a name, email, subject, and message but there is one last problem! I've been following the documentation on emailjs regarding the submission of a form with a name, email, subject, and message, but there is still a problem: I am able to send my message successfully and I receive the data on emailjs and in my gmail mailbox, but I can also submit the empty form! How can I fix this? thank you
import React, { Fragment, useRef } from 'react';
import emailjs from 'emailjs-com';
import { Link } from 'react-router-dom';
import { NotificationContainer, NotificationManager } from 'react-notifications';
function Contact() {
const form = useRef();
const sendEmail = (e) => {
e.preventDefault()
emailjs
.sendForm(
'service_yyyyy',
'template_zzzz',
form.current,
'user_ttttt'
)
.then(
(result) => {
NotificationManager.success('Thank you for trusting us, we come back to you sooner.', 'Successful!', 2000);
}, (error) => {
NotificationManager.error('erreur dans le formulaire!', 'erreurs');
});
e.target.reset()
}
return (
<Fragment>
<div className="regular-page-area section-padding-100">
<div className="container">
<div className="row">
<div className="col-12">
<div className="page-content" style= {{backgroundColor:'white'}}>
<h4>text</h4>
<p>text</p>
</div>
</div>
</div>
</div>
</div>
<section className="medium-padding120 bg-body contact-form-animation scrollme">
<div className="container">
<div className="row">
<div className="col col-xl-10 col-lg-10 col-md-12 col-sm-12 m-auto">
<div className="contact-form-wrap">
<div className="contact-form-thumb">
<div className="col-12">
<div className="section-heading">
<h3 style= {{color:'white'}}>Contact form</h3>
</div>
</div>
<h2 className="title"><span>SEND</span> <span>US YOUR</span><span>MESSAGE</span></h2>
<p>text</p>
<img src={require('../../images/crew.png')} alt="crew" className="crew" />
</div>
<form ref={form} onSubmit={sendEmail} className="contact-form">
<div className="col col-12 col-xl-12 col-lg-12 col-md-12 col-sm-12">
<div className="form-group label-floating">
<label className="control-label"> Name</label>
<input
type="text"
className='form-control'
placeholder='Name'
name='name'
/>
</div>
</div>
<div className="col col-12 col-xl-12 col-lg-12 col-md-12 col-sm-12">
<div className="form-group label-floating">
<label className="control-label"> Email</label>
<input
type="email"
className="form-control"
placeholder="youremail#gmail.com"
name='email'
/>
</div>
<div className="form-group label-floating">
<label className="control-label"> Subject</label>
<input
type='text'
className="form-control"
placeholder="Subject"
name='subject'
/>
</div>
<div className="form-group">
<textarea
name="message"
className="form-control"
placeholder="Your Message"
></textarea>
</div>
<button type="submit" className="btn btn-purple btn-lg full-width">Send Message</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div className="half-height-bg bg-white"></div>
</section>
<NotificationContainer/>
<Footer />
</Fragment>
)
}
export default Contact;

Related

state is not updating in react form validation

I am working with simple form validation in react. The problem here is error message is not displaying in while it is showing in console.log! I am quite new to react and stucked here for quite some time. How can I solve this?
I've seen many youtube videos but nothing is working properly.
const [logindata, setLogindata] = useState({
customeremail: '',
customerpass: ''
})
const [err, seterr] = useState({
Email: '',
Passwordnew: ''
});
const handlechange = event => {
const val = event.target.value
const name = event.target.name
setLogindata({ ...logindata, [name]: val })
console.log(val)
}
function login() {
const NewErr = {...err};
if (logindata.customeremail == "") {
NewErr.Email = "Email should not be empty";
alert(NewErr.Email)
console.log(NewErr)
}
}
return (
<>
<div className="container">
<div className="row">
<div className="col-12 col-sm-12 col-md-6 col-lg-6 main-col offset-md-3">
<div className="mb-4">
<form method="post" action="home" id="CustomerLoginForm" acceptCharset="UTF-8" className="contact-form">
<div className="row">
<div className="col-12 col-sm-12 col-md-12 col-lg-12">
<div className="form-group">
<label htmlFor="CustomerEmail">Email</label>
<input type="email" name="customeremail" placeholder="" id="CustomerEmail" className="" autoCorrect="off" autoCapitalize="off" autoFocus="" onChange={handlechange} value={logindata.customeremail} required = {true} />
</div>
<div className="alert alert-danger" role="alert">
{seterr.Email}
</div>
</div>
<div className="col-12 col-sm-12 col-md-12 col-lg-12">
<div className="form-group">
<label htmlFor="CustomerPassword">Password</label>
<input type="password" name="customerpass" placeholder="" id="CustomerPassword" className="" onChange={handlechange} value={logindata.customerpass} />
</div>
</div>
</div>
<div className="row">
<div className="text-center col-12 col-sm-12 col-md-12 col-lg-12">
<input type="button" style={{ backgroundColor: '#000', color: '#fff' }} className="btn mb-3" value="Sign In" onClick={login} />
<p className="mb-4">
Forgot your password? |
Create account
</p>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</>
There are 2 problem in your code
1. Not setting state
You are not setting state for err using seterr as:
if (logindata.customeremail == '') {
NewErr.Email = 'Email should not be empty';
alert(NewErr.Email);
console.log(NewErr);
seterr(NewErr); // MISSING
}
CODESANDBOX LINK
2. Showing error message with wrong way
When you use useState then it will give you an array of value and function through which you can update the value and on change of the value it will re-render it. You have to use err obj not the function seterr.
You should use {err.Email}} instead of {seterr.Email}}
<div className='alert alert-danger' role='alert'>
{/* {seterr.Email} */}
{err.Email}
</div>;

How can I export a variable to another file React

I am doing a program which gets information from the https://api.randomuser.me/ API. I got the fetch call working but my goal is to display the information as prefilled information in a form located in another file, but I don't know how I should export the variables and how to use them in the other file.
This is my FetchCall.js:
import Axios from 'axios'
import { useState } from 'react';
function FetchCall() {
const[name,setName] = useState("")
const[birth,setBirth] = useState("")
const[email,setEmail] = useState("")
const[insuranceNo, setInsuranceNo] = useState("")
const[phoneNo, setPhoneNo] = useState("")
const getInfo = () => {
Axios.get("https://api.randomuser.me/").then(
(response) => {
setName(response.data.results[0].name.first + " " + response.data.results[0].name.last);
setBirth(response.data.results[0].dob.date);
setEmail(response.data.results[0].email)
setInsuranceNo(response.data.results[0].login.sha1)
setPhoneNo(response.data.results[0].phone)
}
);
};
return(
<div>
Hello
<button onClick={getInfo}>Get User</button>
<div>
{name}
</div>
<div>
{birth}
</div>
<div>
{email}
</div>
<div>
{insuranceNo}
</div>
<div>
{phoneNo}
</div>
</div>
);
}
export default FetchCall;
And here is where I want to export the variables (name, birth,email, insuranceNo,phoneNo)
import FetchCall from './fetchCall';
function InputTextFilled() {
return (
<div className="inputText has-text-left">
<fieldset disabled>
<div className="field">
<div className="control">
<p className="label">Full Name</p>
<input className="input" type="text" value="VARIABLEHERE" />
</div>
<div className="control mt-5">
<a className="label">Date of Birth</a>
<input className="input" type="text" value="VARIABLEHERE" />
</div>
<div className="control mt-5">
<p className="label">National Insurance Number</p>
<input className="input" type="text" value="VARIABLEHERE" />
</div>
<div className="control mt-5">
<p className="label">Email Address</p>
<input className="input" type="text" value="VARIABLEHERE" />
</div>
<div className="control mt-5">
<p className="label">Telephone Number</p>
<input className="input" type="text" value="VARIABLEHERE" />
</div>
</div>
</fieldset>
</div>
);
}
export default InputTextFilled;
React Props are like function arguments in JavaScript and attributes in HTML.
To send props into a component, use the same syntax as HTML attributes.
import Axios from "axios";
import { useState } from "react";
function FetchCall() {
const [name, setName] = useState("");
const [birth, setBirth] = useState("");
const [email, setEmail] = useState("");
const [insuranceNo, setInsuranceNo] = useState("");
const [phoneNo, setPhoneNo] = useState("");
const getInfo = () => {
Axios.get("https://api.randomuser.me/").then((response) => {
setName(
response.data.results[0].name.first +
" " +
response.data.results[0].name.last
);
setBirth(response.data.results[0].dob.date);
setEmail(response.data.results[0].email);
setInsuranceNo(response.data.results[0].login.sha1);
setPhoneNo(response.data.results[0].phone);
});
};
return (
<div>
Hello
<button onClick={getInfo}>Get User</button>
<div>{name}</div>
<div>{birth}</div>
<div>{email}</div>
<div>{insuranceNo}</div>
<div>{phoneNo}</div>
{/* //This is the child compoennt */}
<DisplayExample1
name={name}
birth={birth}
email={email}
insuranceNo={insuranceNo}
phoneNo={phoneNo}
/>
<DisplayExample2
name={name}
birth={birth}
email={email}
insuranceNo={insuranceNo}
phoneNo={phoneNo}
/>
</div>
);
}
export default FetchCall;
In a functional stateless component, the props are received in the function signature as arguments:
//Child Component Example 1
const DisplayExample1 = ({ name, birth, insuranceNo, phoneNo }) => (
<div className="inputText has-text-left">
<fieldset disabled>
<div className="field">
<div className="control">
<p className="label">Full Name</p>
<input className="input" type="text" value={name} />
</div>
<div className="control mt-5">
<a className="label">Date of Birth</a>
<input className="input" type="text" value={birth} />
</div>
<div className="control mt-5">
<p className="label">National Insurance Number</p>
<input className="input" type="text" value={insuranceNo} />
</div>
<div className="control mt-5">
<p className="label">Email Address</p>
<input className="input" type="text" value={email} />
</div>
<div className="control mt-5">
<p className="label">Telephone Number</p>
<input className="input" type="text" value={phoneNo} />
</div>
</div>
</fieldset>
</div>
);
React's props can pass data in React by defining custom HTML attributes to which you assign your data with JSX syntax. So don't forget the curly braces.
//Child Component Example 2 (Class Component)
class DisplayExample2 extends Component {
render() {
return (
<div className="inputText has-text-left">
<fieldset disabled>
<div className="field">
<div className="control">
<p className="label">Full Name</p>
<input className="input" type="text" value={this.props.name} />
</div>
<div className="control mt-5">
<a className="label">Date of Birth</a>
<input className="input" type="text" value={this.props.birth} />
</div>
<div className="control mt-5">
<p className="label">National Insurance Number</p>
<input
className="input"
type="text"
value={this.props.insuranceNo}
/>
</div>
<div className="control mt-5">
<p className="label">Email Address</p>
<input className="input" type="text" value={this.props.email} />
</div>
<div className="control mt-5">
<p className="label">Telephone Number</p>
<input className="input" type="text" value={this.props.phoneNo} />
</div>
</div>
</fieldset>
</div>
);
}
}

How to use colons in const

New to react and I am trying to use a colon like so (within the return of ProfilePage.js):
<a class="uk-text">{user.attributes.custom:company_name}</a>
but its giving me this error:
Parsing error: Unexpected token, expected "}"
I am getting attributes from an AWS Cognito User Pool and I can successfully see the returned object if I log it to the console like so:
Object >
custom:company_name: "apple"
custom:department: "dept"
custom:job_title: "title"
email: "email#me.com"
email_verified: false
family_name: "user"
given_name: "test"
locale: "location"
phone_number: "+18702831861"
phone_number_verified: false
sub: "guid"
I can get the family_name without issue:
<a class="uk-text">{user.attributes.family_name}</a>
but anytime I try the custom attributes with its colon, it throws the error.
Full ProfilePage.js code:
import React from "react";
import { API, graphqlOperation } from 'aws-amplify';
class ProfilePage extends React.Component {
state = {
};
componentDidMount() {
if (this.props.user) {
}
}
render() {
const { user } = this.props;
console.log(user.attributes)
const emailVerified = this.props.user.attributes.email_verified
const company_name = user.attributes.custom:company_name; // ERROR occurs here
return (
<>
<div class="container">
<div class="uk-margin-medium-top">
<ul class="uk-flex-center uk-tab">
<li class="uk-active"><a>Profile Summary</a></li>
</ul>
</div>
{/* Cards */}
<div class="uk-section">
<div class="uk-child-width-1-3#m uk-grid-small uk-grid-match uk-grid">
<div>
<div class="uk-card uk-card-default uk-card-body">
<h3 class="uk-card-title">User</h3>
<p>
{/* Form */}
<form class="uk-form-stacked">
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">User ID</label>
<div class="uk-form-controls">
<a class="uk-text-muted uk-link-reset">{user.attributes.sub}</a>
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">First Name</label>
<div class="uk-form-controls">
<a class="uk-text">{user.attributes.given_name}</a>
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Last Name</label>
<div class="uk-form-controls">
<a class="uk-text">{user.attributes.family_name}</a>
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Email <a class="uk-label uk-text-link">{emailVerified}</a></label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="text" placeholder={user.attributes.email} />
</div>
</div>
</form>
</p>
</div>
</div>
<div>
<div class="uk-card uk-card-primary uk-card-body">
<h3 class="uk-card-title">Company</h3>
<p>
{/* Form */}
<form class="uk-form-stacked">
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Name</label>
<div class="uk-form-controls">
<a class="uk-text">{company_name}</a>
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Role</label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="text" placeholder="Some text..." />
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Description</label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="text" placeholder="Some text..." />
</div>
</div>
</form>
</p>
</div>
</div>
<div>
<div class="uk-card uk-card-secondary uk-card-body">
<h3 class="uk-card-title">Security</h3>
<p>
{/* Form */}
<form class="uk-form-stacked">
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Change Password</label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="text" placeholder="Some text..." />
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Multi-Factor Authenication</label>
<div class="uk-form-controls">
<input class="uk-input" id="form-stacked-text" type="text" placeholder="Some text..." />
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Delete Account</label>
<div class="uk-form-controls">
<button class="uk-button uk-button-primary">Delete Account Forever</button>
</div>
</div>
</form>
</p>
</div>
</div>
</div>
</div>
</div>
</>
)
}
}
export default ProfilePage;
I do not even know what this use is called {user.attributes.custom:company_name}, reference to a const? Can someone educate me on what that is named and how do I use a colon within one?
Regards
You can access object's properties with brackets as well.
<a class="uk-text">{user.attributes["custom:company_name"]}</a>
Since a colon isn't a valid character for variables, object properties (because it's used to set a value to some property), you have to define/get the value with wrapping the name with quotes.
Hope I got the problem correctly.

How to set value of an input from Redux store, but then still be able to write in that input and update value?

My input is also like a searchbox: I want to be able to search for names on the input but then I want to be able to click a name from the dropdown search results and set the input with that value. I then want to be able to search again if I want to change that value.
Tried using DefaultValue and uncontrolled components, but neither worked. Not sure if I used them right though.
class PublishTest extends Component {
constructor() {
super();
this.state = {
showRows: false,
numberOfRows: ["row"],
search: "",
searchResults: [],
insightListActive: false,
insightTagsActive: false
};
this.hideOrShowRows = this.hideOrShowRows.bind(this);
this.addNewRow = this.addNewRow.bind(this);
this.searchAllUsers = this.searchAllUsers.bind(this);
this.onChangeInsight = this.onChangeInsight.bind(this);
this.clearInput = this.clearInput.bind(this);
this.clearInsightList = this.clearInsightList.bind(this);
this.searchInsightTags = this.searchInsightTags.bind(this);
this.clearTagList = this.clearTagList.bind(this);
}
componentDidMount() {
this.props.getLoginCredential();
this.props.getAllRoles();
}
hideOrShowRows() {
this.setState({
showRows: !this.state.showRows
});
}
addNewRow() {
this.setState({
numberOfRows: [...this.state.numberOfRows, "row"]
});
}
searchAllUsers(e) {
this.setState({
search: e.target.value
});
const searchOption = this.state.search;
fetch("http://localhost:3500/soiapi/", {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
data: [
{
name: "searchUser",
urlparameter: { search: searchOption, appId: "1" },
parameter: ""
}
]
})
})
.then(res => res.json())
.then(data => {
this.setState({
searchResults: data[0]
});
});
}
onChangeInsight = e => {
this.props.insightOnChangeValue(e.target.value);
this.props.searchInsights(e.target.value);
this.setState({
insightListActive: true
});
};
clearInput() {
this.setState({
search: "",
searchResults: []
});
}
clearInsightList() {
this.setState({
insightListActive: false
});
}
searchInsightTags(e) {
this.props.getInsightTags(e.target.value);
this.setState({
insightTagsActive: true
});
}
clearTagList() {
this.setState({
insightTagsActive: false
});
}
render() {
const { searchResults } = this.state;
let rows;
let button;
let icon;
if (this.state.showRows) {
rows = this.state.numberOfRows.map((row, i) => (
<div>
<Row index={i} />
</div>
));
button = (
<button
onClick={this.addNewRow}
className="Button--secondary float-right"
>
Add Row
</button>
);
icon = (
<i aria-hidden="true" className="Icon Icon--minus-small iconFont"></i>
);
} else if (!this.state.showRows) {
icon = (
<i aria-hidden="true" className="Icon Icon--plus-small iconFont"></i>
);
}
if (this.props.user.userDTO) {
const { userDTO } = this.props.user;
const insightSearchResults = this.props.insightReducerValue
.insightList[0];
return (
<div style={{ padding: "5px" }} className="publish-container">
<h4 className="publish-h4">Publish Insights</h4>
<h6 className="publish-h6">Insight Details</h6>
<hr className="line-style" />
<section id="publish-section-1">
<div class="Grid">
<div class="Col Col--3">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label insight-label">
Insight Name <span className="asterisk">*</span>:
</label>
<div id="insight-container">
<input
type="text"
placeholder="Insight Name"
onChange={this.onChangeInsight}
onFocus={this.clearInsightList}
onBlur={this.clearInsightList}
className="Form-input"
value={this.props.insightReducerValue.insightValue}
/>
{this.state.insightListActive ? (
<InsightList insights={insightSearchResults} />
) : null}
</div>
</div>
</div>
</div>
<div class="Col Col--3">
<div class="grid-block">
<div class="Form-group publish-insights-input">
<label class="Form-label">
Insight Source <span className="asterisk">*</span>:
</label>
<select
id="insight-source"
role="combobox"
class="Form-input"
>
<option
disabled="disabled"
selected="selected"
aria-disabled="true"
>
Choose one
</option>
<option>Tableau</option>
<option>Qlik</option>
<option>D3JS</option>
<option>CXI</option>
</select>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-2">
<div class="Grid">
<div class="Col Col--6">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label class="Form-label">
URL <span className="asterisk">*</span>:
</label>
<input type="text" placeholder="URL" class="Form-input" />
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-3">
<div class="Grid">
<div class="Col Col--6">
<div class="grid-block">
<div className="publish-insights-input">
<label class="Form-label">
Description <span className="asterisk">*</span>:
</label>
<textarea
placeholder="Description"
class="Form-input"
></textarea>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-4">
<div class="Grid">
<div class="Col Col--3">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label third-div-p">
POC Name <span className="asterisk">*</span>:
</label>
<input
type="text"
placeholder="Name"
className="Form-input"
value={`${userDTO.firstName} ${userDTO.lastName}`}
/>
</div>
</div>
</div>
<div class="Col Col--3">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label third-div-p">
Group Distro (E-mail Address)
<span className="asterisk">*</span>:
</label>
<input
type="text"
placeholder="Email"
class="Form-input"
value={userDTO.emailAddress}
/>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-5">
<div class="Grid">
<div class="Col Col--6">
<div class="grid-block">
<div class="Form-group publish-insights-input">
<div class="Form-checkbox is-restricted">
<input
id="restricted"
name="checkboxDefault"
type="checkbox"
/>
<label for="restricted">Is Restricted</label>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-6">
<div class="Grid">
<div class="Col Col--2">
<div class="grid-block">
<div id="tree-section">
<label id="category-label" className="Form-label">
Category <span className="asterisk">*</span>
</label>
<div id="tree-container">
<PublishInsightsTree />
</div>
</div>
</div>
</div>
<div class="Col Col--4">
<div class="grid-block">
<div className="Form-group publish-insights-input">
<label className="Form-label third-div-p">
Add Insight Tags <span className="asterisk">*</span>:
</label>
<input
type="text"
onChange={e => this.searchInsightTags(e)}
onFocus={this.clearTagList}
onBlur={this.clearTagList}
placeholder="Write some insight tags"
className="Form-input"
/>
</div>
{
this.state.insightTagsActive ?
<div>
{
this.props.insightTags ?
<InsightTags tags={this.props.insightTags[0]} />
: null
}
</div>
: null
}
</div>
<div class="grid-block">
<div class="Grid">
<div class="Col Col--7 img-url-input">
<div class="grid-block">
<div
id="file-div"
class="Form-group publish-insights-input"
>
<label class="Form-label">
Image URL <span className="asterisk">*</span>:
</label>
<input
type="text"
placeholder="Insight Name"
class="Form-input"
/>
</div>
</div>
</div>
<div class="Col Col--5">
<div class="grid-block">
<button class="Button--secondary upload-image-button">
Upload Image
</button>
</div>
</div>
<div class="Col Col--7 url-description">
<div class="grid-block">
<p>
Please copy paste the generated URL after uploading
image file.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-7">
<h6 className="publish-h6">Role Details</h6>
<hr className="line-style" />
</section>
<section id="publish-section-8">
<div class="Grid">
<div class="Col Col--2">
<div class="grid-block">
<label id="roles-label" className="Form-label">
Assign to Role <span className="asterisk">*</span>
</label>
<div id="all-roles">
{this.props.listOfRoles ? (
<ListOfRoles roles={this.props.listOfRoles} />
) : null}
</div>
</div>
</div>
<div class="Col Col--4">
<div class="grid-block assign-user-div">
<label className="Form-label label-spacing">
Assign to Individual User:
</label>
<div className="Form-group">
<textarea
onChange={this.searchAllUsers}
type="text"
placeholder="Look up by EID/Name"
onFocus={this.clearInput}
onBlur={this.clearInput}
className="Form-input assign-user-textarea"
value={this.state.search}
></textarea>
{searchResults.length > 0 ? (
<div id="user-list">
{searchResults ? (
<UserList searchResults={this.state.searchResults} />
) : null}
</div>
) : null}
</div>
</div>
</div>
</div>
</section>
<section id="publish-section-9">
<h6 className="publish-h6 metadata-heading" onClick={this.hideOrShowRows}>
<span id="metadata-icon">{icon}</span>
Metadata Info
</h6>
<hr className="line-style color" />
</section>
<section id="publish-section-10">
<div class="Grid">
<div class="Col Col--12 add-row-col">
<div class="grid-block">{button}</div>
</div>
</div>
{rows}
</section>
</div>
);
} else {
return null;
}
}
}
const mapStateToProps = state => ({
user: state.LoginReducer.loginInfo,
searchUser: state.LoginReducer.searchUser,
insightReducerValue: state.SideDrawerReducer,
listOfRoles: state.LoginReducer.listOfRoles,
insightTags: state.SideDrawerReducer.insightTags
});
export default connect(
mapStateToProps,
{
getLoginCredential,
searchUser,
insightOnChangeValue,
searchInsights,
getAllRoles,
getInsightTags
}
)(PublishTest);
This is the part of the code I need help with:
<input
type="text"
placeholder="Insight Name"
onChange={this.onChangeInsight}
onFocus={this.clearInsightList}
onBlur={this.clearInsightList}
className="Form-input"
value={this.props.insightReducerValue.insightValue}
/>
{this.state.insightListActive ? (
<InsightList insights={insightSearchResults} />
) : null}
Since your code is a little messy, I made a sandbox that fetches some data from a dummy API, stores that data to our local component state. We have a text field where we can type in usernames and a list of matching usernames will appear as a dummy drop, clicking any one of those usernames will set the value in the text field. It's pretty straight forward will give you an idea on how to get started.
EDIT:
Sandbox Link: https://codesandbox.io/s/eloquent-pascal-pf3hd?fontsize=14
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
state = {
input: "",
users: [],
dropdown: []
};
async componentDidMount() {
let users = await fetch("https://jsonplaceholder.typicode.com/users");
users = await users.json();
this.setState({ users });
}
handleChange = e => {
this.setState({ input: e.target.value }, () => {
let results = this.state.users.filter(user => {
return user.username.indexOf(this.state.input) > -1;
});
this.setState({ dropdown: results });
});
};
handleSelect = username => e => {
this.setState({ input: username }, () => this.setState({ dropdown: [] }));
};
render() {
return (
<div className="App">
<h1>Search</h1>
<input
type="text"
name="input"
onChange={this.handleChange}
value={this.state.input}
/>
{this.state.dropdown.map(d => (
<h3 onClick={this.handleSelect(d.username)} key={d.id}>
{d.username}
</h3>
))}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Could you start off by loading all possible search results into state or props (e.g. under this.props.searchResults)? Then you could try using the datalist tag. Not quite sure if this was what you were going for, but it looked like something like that could work for you.
<input type="text"
defaultValue={this.props.insightReducerValue.insightValue}
list="inputOptions"
onChange={(e) => console.log("Current input field value: ", e.target.value)} />
<datalist id="inputOptions">
{this.props.searchResults.map((item, key) =>
<option key={key} value={item} />
)}
</datalist>
P.S. Check the supported browsers list under the link.

send what its capured from a form to the actions file React/Redux

I want to send that state of a component to the actions file.
My component is a <form> where the user can capture some config that later i want to apply that config to the actions file.
Component Code:
import React, { Component } from 'react';
class AdminConfig extends Component{
constructor(props){
super(props);
this.state=({
baseURL:'BASE_URL',
hospitalName: '',
hospitalExternalID:'1000849',
payerName:'',
payerAddress:''
})
this.onBaseURLChange = this.onBaseURLChange.bind(this);
this.onHospitalNameChange = this.onHospitalNameChange.bind(this);
this.onHospitalExIDChange = this.onHospitalExIDChange.bind(this);
this.onPayerNameChange = this.onPayerNameChange.bind(this);
this.onPayerAddressChange = this.onPayerAddressChange.bind(this);
this.onAdminFormSubmit = this.onAdminFormSubmit.bind(this);
}
onBaseURLChange(e){
this.setState({
baseURL: e.target.value
})
}
onHospitalNameChange(e){
this.setState({
hospitalName: e.target.value
})
}
onHospitalExIDChange(e){
}
onPayerNameChange(e){
this.setState({
payerName: e.target.value
})
}
onPayerAddressChange(e){
this.setState({
payerAddress: e.target.value
})
}
onAdminFormSubmit(e){
e.preventDefault()
// here is where i need to send something like this:
this.props.fetchAdminConfig(this.state.baseURL)
}
render(){
return(
<div className="container ">
<form className="admin-form" onSubmit={this.onAdminFormSubmit}>
<div className="row">
<div className="jumbotron col-md-12">
<h4>API CONFIGURATION</h4>
</div>
<div className="col-md-12">
<div className="panel panel-primary">
<div className="panel-heading">BASE URL</div>
<div className="panel-body">
<input
onChange={this.onBaseURLChange}
type="text"
className="form-control"
id="baseURL"
placeholder="Base URL" />
<div className="panel-body" id="getResult"> <p className="">Base URL: http://{this.state.baseURL}/trucare-api-6.2.1.TC621/6.2.1/api</p></div>
</div>
</div>
</div>
</div>
<div className="row">
<div className="jumbotron col-md-12">
<h4>HOSPITAL INFORMATION</h4>
</div>
<div className="col-md-6">
<div className="panel panel-primary">
<div className="panel-heading">Hospital Name</div>
<div className="panel-body">
<input
onChange={this.onHospitalNameChange}
type="text"
className="form-control"
id="hospitalName"
placeholder="Hospital Name" />
<div className="panel-body" id="getResult"><p className="">Hospital name: {this.state.hospitalName}</p></div>
</div>
</div>
</div>
<div className="col-md-6">
<div className="panel panel-primary">
<div className="panel-heading">Hospital External ID</div>
<div className="panel-body">
<input
onChange={this.onHospitalExIDChange}
type="text"
className="form-control"
id="hospitalEXID"
placeholder="Hospital Name" disabled />
<div className="panel-body" id="getResult"><p>Hospital External ID: {this.state.hospitalExternalID}</p></div>
</div>
</div>
</div>
</div>
<div className="row">
<div className="jumbotron col-md-12">
<h4>PAYER INFORMATION</h4>
</div>
<div className="col-md-6">
<div className="panel panel-primary">
<div className="panel-heading">Payer Name</div>
<div className="panel-body">
<input
onChange={this.onPayerNameChange}
type="text"
className="form-control"
id="payerName"
placeholder="Payer Name" />
<div className="panel-body" id="getResult"><p>Payer Name: {this.state.payerName}</p></div>
</div>
</div>
</div>
<div className="col-md-6">
<div className="panel panel-primary">
<div className="panel-heading">Payer Address</div>
<div className="panel-body">
<input
onChange={this.onPayerAddressChange}
type="text"
className="form-control"
id="payerAddress"
placeholder="Payer Address" />
<div className="panel-body" id="getResult"><p>Payer Address: {this.state.payerAddress}</p></div>
</div>
</div>
</div>
</div>
<button type="submit" className="btn btn-primary btn-lg">Apply config</button>
</form>
</div>
);
}
}
export default AdminConfig
Then on my actions file I have this:
export function fetchAdminConfig(BASE_URL){
...
}
const BASE_URL = //this is where I want to apply the state that I captued on my form
export function fetchUsers() {
const request = axios.post(`${BASE_URL}/endpoint`)
return {
type: FETCH_USERS,
payload: request
};
}
How Can I accomplish this?
Just add a parameter to your action creator function and pass it in!
export function fetchAdminConfig(BASE_URL) {
const request = axios.post(`${BASE_URL}/endpoint`)
return {
type: FETCH_USERS,
payload: request
};
}

Resources