How can I export a variable to another file React - reactjs

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>
);
}
}

Related

How calculate the marks using switch in react?

I created the few questions page I want calculate marks when click the submit button but when I click submit button marks didn't show.
This my code code . In this code I get the values from the checkbox and input to switch case and calculate the marks but marks doesn't show and not redirect to '/questions/markspage/${marks}' this page.
code
function InAnswers() {
const history = useHistory();
const [answers, setAnswers] = useState('');
const [question, setQuestion] = useState('');
const [dayWord, setDayWord] = useState(''); //1
const [seeObject, setSeeObject] = useState(''); //2
const [identifyObject, setIdentifyObject] = useState(''); //3
const [identifyColor, setIdentifyColor] = useState(''); //4
const [firstWord, setFirstWord] = useState(''); //5
const [marks, setMarks] = useState(''); //5
async function submitMarks(event) {
event.preventDefault();
var marks = 0;
switch (marks) {
case 'wordday' == 'wordmore5':
setMarks(marks + 10);
return setMarks;
break;
case 'see' == 'yessee ':
setMarks(marks + 10);
return setMarks;
break;
case 'identify' == 'yesidentify':
setMarks(marks + 10);
return setMarks;
break;
case 'colors' == 'colorsyes ':
setMarks(marks + 10);
return setMarks;
break;
case 'firstword' == 'firstword18 ':
setMarks(marks + 10);
return setMarks;
break;
default:
setMarks(marks + 10);
return setMarks;
history.push(`/questions/markspage/${marks}`);
}
}
// // calculate marks
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<div className='pb-2 px-3 d-flex flex-wrap align-items-center justify-content-between'>
<h2>Questions </h2>
</div>
</div>
<div className='col-3'></div>
</div>
{/* </div> */}
<div className='row'>
<h4 className='mb-4'> Questions </h4>
<form onSubmit={submitMarks}>
<div>
<div className='progressCard'>
<div className='p-3'>
<h2>1. how many words child talk in a day?</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='wordday'
id='wordless5'
value='wordless5'
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='wordless5'>
less 5
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='wordday'
id='wordmore5'
value='wordmore5'
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='wordmore5'>
more than 5
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>
2. when you show some thing to child then is child watch
there?
</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='see'
id='nosee'
value='nosee'
required
onChange={(e) => setSeeObject(e.target.value)}
/>
<label className='form-check-label' for='PUBLISH'>
no
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='see'
id='yessee'
value='yessee'
required
onChange={(e) => setSeeObject(e.target.value)}
/>
<label className='form-check-label' for='UNPUBLISH'>
yes
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>3.When you show some thing then is child identify that </h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='identify'
id='noidentify'
value='noidentify'
required
onChange={(e) => setIdentifyObject(e.target.value)}
/>
<label className='form-check-label' for='PUBLISH'>
no
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='identify'
id='yesidentify'
value='yesidentify'
required
onChange={(e) => setIdentifyObject(e.target.value)}
/>
<label className='form-check-label' for='UNPUBLISH'>
yes
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>4. child can identify more than 5 colors</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='colors'
id='colorsno'
value='colorsno'
required
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='PUBLISH'>
no
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='colors'
id='colorsyes'
value='colorsyes'
required
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='UNPUBLISH'>
yes
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>5.The first word child told?</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='firstword'
id='firstword19'
value='firstword19'
required
onChange={(e) => setFirstWord(e.target.value)}
/>
<label className='form-check-label' for='firstword19'>
after 18 months
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='firstword'
id='firstword18'
value='firstword18'
required
onChange={(e) => setFirstWord(e.target.value)}
/>
<label className='form-check-label' for='firstword18'>
before 18 months
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
</div>
</form>
<div className='col-xl-6 mb-4'></div>
<div>
<input
type='submit'
value='SUBMIT ANSWERS '
className='form-submit-btn'
/>
</div>
</div>
</div>
);
}
export default InAnswers;
You should define the submit input inside the <form> tag:
<form onSubmit={submitMarks}>
...
<div className='col-xl-6 mb-4'></div>
<div>
<input
type='submit'
value='SUBMIT ANSWERS '
className='form-submit-btn'
/>
</div>
</form>
If you need to calculate the total for marks given the responses you should rewrite the submitMarks function as:
function submitMarks(event) {
event.preventDefault();
var marks = 0;
if (dayWord === 'wordmore5') marks += 10;
if (seeObject === 'yessee') marks += 10;
if (identifyObject === 'yesidentify') marks += 10;
if (identifyColor === 'colorsyes') marks += 10;
if (firstWord === 'firstword18') marks += 10;
history.push(`/questions/markspage/${marks}`);
}
No need to declare it async nor declare a separate marks state variable.

EmailJs and Form validation control

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;

Changing state in useEffect

I am dispatching an action in useEffect hook to fetch data and then updating state using the data from redux store. When the page first loads i get the correct data, but when refreshing the browser I get undefined values.
React.useEffect(() => {
dispatch(getSingleCoin(props.match.params.id))
setName(coinDetail.name)
setSymbol(coinDetail.symbol)
setLogourl(coinDetail.logo)
setPrice(coinDetail.price)
setLaunchDate(coinDetail.launchDate)
setWebsiteUrl(coinDetail.websiteUrl)
setNetwork(coinDetail.chain)
setAddress(coinDetail.address)
setTwitterUrl(coinDetail.twitter)
setTelegramUrl(coinDetail.telegram)
setRedditUrl(coinDetail.reddit)
setYoutubeUrl(coinDetail.youtube)
setCoinDescription(coinDetail.description)
setMarketCap(coinDetail.marketCap)
}
}, [coinDetail,dispatch, props.match.params.id])
const handleSubmit = (e) => {
e.preventDefault()
const coin = {}
coin.name = name
coin.symbol = symbol
coin.logo = logourl
coin.price = price
coin.launchDate = launchDate
coin.websiteUrl = websiteUrl
coin.chain = network
coin.address = address
coin.twitter = twitterUrl
coin.telegram = telegramUrl
coin.reddit = redditUrl
coin.youtube = youtube
coin.description = coinDescription
coin.marketCap = marketCap
coin._id = props.match.params.id
dispatch(updateCoin(coin))
}
return (
<div className="container add-coin-wapper mt-4">
{loading && coinDetail === undefined ? (
<div>...Loading</div>
) : error ? (
<div>{error}</div>
) : (
<div className="card ">
<div className="card-header">
<div className="approve-header">
<div
className="approve-back"
onClick={() => props.history.push('/Admin/coinlist')}
>
<ArrowBackIosIcon />
<div>Back to Coin listing</div>
</div>
</div>
</div>
<div className="card-body">
{/* here */}
<>
<div>
<h3>Edit Coin</h3>
</div>
<form onSubmit={handleSubmit}>
<div className="row">
<div className="col-sm-12 col-md-6 col-lg-6">
<h5>Coin informations</h5>
<div className="form-group">
<label htmlFor="name">name</label>
<input
type="text"
className="form-control"
id="name"
name="name"
placeholder="Bitcoin"
required
onChange={(e) => setName(e.target.value)}
value={name}
/>
</div>
<div className="form-group">
<label htmlFor="symbol">symbol</label>
<input
type="text"
className="form-control"
id="symbol"
name="symbol"
placeholder="Enter symbol"
onChange={(e) => setSymbol(e.target.value)}
required
value={symbol}
/>
</div>
<div className="form-group">
<label htmlFor="logo">Logo url</label>
<input
type="text"
className="form-control"
id="url"
name="logourl"
placeholder="https://clod.com/logo"
onChange={(e) => setLogourl(e.target.value)}
value={logourl}
/>
</div>
<div className="form-group">
<label htmlFor="description">Coin Description</label>
<textarea
className="form-control"
id="exampleFormControlTextarea1"
rows="3"
onChange={(e) => setCoinDescription(e.target.value)}
placeholder="Describe your coin appropriately to show attractiveness"
value={coinDescription}
></textarea>
</div>
<div className="form-group">
<label htmlFor="price">price</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">$</div>
</div>
<input
type="number"
className="form-control"
id="marketcap"
placeholder="0.00085"
step="any"
min="0"
onChange={(e) => setPrice(e.target.value)}
value={price}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="marketcap">Market cap</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">$</div>
</div>
<input
type="number"
className="form-control"
id="marketcap"
step="any"
placeholder="0.00085"
min="0"
onChange={(e) => setMarketCap(e.target.value)}
value={marketCap}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="launchdate">Launch date</label>
<div
className="input-group date"
data-provide="datepicker"
>
<input
type="date"
className="form-control"
onChange={(e) => setLaunchDate(e.target.value)}
value={moment(launchDate).format('YYYY-MM-DD')}
/>
<div className="input-group-addon">
<span className="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</div>
<div className="col-sm-12 col-md-6 col-lg-6">
<h5>Coin market</h5>
<div className="form-group">
<label htmlFor="network">Network/Chain</label>
<select
className="form-control"
id="network"
onChange={(e) => setNetwork(e.target.value)}
value={network}
>
<option value="BSC">Binance Smart Chain (BSC)</option>
<option value="ETH">Ethereum (ETH)</option>
<option value="SOL">Solona (SOL)</option>
</select>
</div>
<div className="form-group">
<label htmlFor="contract">Contract Adress</label>
<input
type="text"
className="form-control"
id="contract"
name="contract"
placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
onChange={(e) => setAddress(e.target.value)}
required
value={address}
/>
</div>
<h5>Coin links</h5>
<div className="form-group">
<label htmlFor="weburl">Website url</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<LanguageIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="web"
placeholder="https://www.coinx.com"
onChange={(e) => setWebsiteUrl(e.target.value)}
required
value={websiteUrl}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="twitter">Twitter</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<TwitterIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="twitter"
placeholder="https://twitter.com/"
onChange={(e) => setTwitterUrl(e.target.value)}
value={twitterUrl}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="telegram">Telegram</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<TelegramIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="telegram"
placeholder="https://t.me/"
onChange={(e) => setTelegramUrl(e.target.value)}
value={telegramUrl}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="youtube">YouTube</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<YouTubeIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="youtube"
placeholder="https://www.youtube.com/watch?v="
onChange={(e) => setYoutubeUrl(e.target.value)}
value={youtube}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="reddit">Reddit</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<RedditIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="reddit"
placeholder="https://www.reddit.com"
onChange={(e) => setRedditUrl(e.target.value)}
value={redditUrl}
/>
</div>
</div>
<button type="submit" className="btn" disabled={loading}>
update
</button>
</div>
</div>
</form>
</>
{/* here */}
</div>
{/* here */}
</div>
)}
</div>
The state data is supposed to be displayed in form input elements. I render a div with a loading status before the data is fetched and loading set to false.

Reactjs - how can i take input from one component(inputbox) and use it in other component

I am building a MOVIE Search API app and I am taking input from one serah input box from the user with help of following code
import React, { Component } from "react";
import styles from "../styles/Example.module.css";
import Appletv from "../appletv.json";
import Link from 'next/link';
export default class example extends Component {
constructor(props) {
super(props);
this.state = {
movies: "",
filteredShows: Appletv.shows, // Starting with all shows
};
}
handMoviesChange = (event) => {
this.setState({
movies: event.target.value,
});
};
handleSubmit = (event) => {
event.preventDefault();
const newFilteredShows = Appletv.shows.filter((show) => {
return (
this.state.movies === "" ||
show.Title.toLowerCase().includes(this.state.movies.toLowerCase())
);
});
this.setState({ filteredShows: newFilteredShows });
};
render() {
console.table(Appletv.shows);
return (
<div className={styles.container}>
<h3 className={styles.Title}>SearchTest</h3>
<form onSubmit={this.handleSubmit}>
<div className={styles.row}>
<input
className={styles.input}
id="search"
type="input"
required
placeholder="Please enter title"
value={this.state.movies}
onChange={this.handMoviesChange}
/>
</div>
<Link href="/searchtest">
<button className={styles.button} type="submit">
Search
</button>
</Link>
</form>
<div className={styles.results} >
{this.state.filteredShows.map((filteredShows, index) => {
return (
<div>
{/* <h1 className={styles.title}>{filteredShows.Title}</h1>
<img
className={styles.image}
src={filteredShows.Thumbnail}
alt="Thumbnail"
/>
<h5 className={styles.genre}>
{filteredShows.Genre} & {filteredShows["Release date"]}
</h5>
<p className={styles.desc}>{filteredShows.Description}</p> */}
</div>
);
})}
</div>
</div>
);
}
}
Output of this code is following
and I want to get those results in the second component and second component code is following
import React, { Component, useState } from "react";
import styles from "../styles/Home.module.css";
import Appletv from "../appletv.json";
import Pagination from "./components/Pagination";
/* import Netflixlogo from "../logos/netflix.png";
*//* import Appletvlogo from "../logos/appletv.png";
import dstvlogo from "../logos/dstv.png";
import Amzonlogo from "../logos/amzon.png";
import Showmaxlogo from "../logos/showmax.png"; */
export default class searchtest extends Component {
constructor(props) {
super(props);
this.state = {
movies: "",
filteredShows: Appletv.shows, // Starting with all shows
};
}
handMoviesChange = (event) => {
this.setState({
movies: event.target.value,
});
};
handleSubmit = (event) => {
event.preventDefault();
/* const filteredShows = array.slice(0, 6);
*/
const newFilteredShows = Appletv.shows.filter((show) => {
return (
this.state.movies === "" ||
show.Title.toLowerCase().includes(this.state.movies.toLowerCase())
);
});
this.setState({ filteredShows: newFilteredShows });
};
render() {
console.table(Appletv.shows);
return (
<div className={styles.container}>
{/* <h3 className={styles.Title}>SearchTest</h3>
*/}
{/* <h4 className={styles.searche}>Search Results</h4>
*/}{" "}
<input
className={styles.searchin}
id="search"
type="input"
required
placeholder="Please enter title"
value={this.state.movies}
onChange={this.handMoviesChange}
/>{" "}
<button className={styles.searchbtn} type="submit">
Search
</button>{" "}
<div className={styles.row}>
<form onSubmit={this.handleSubmit}>
<div className={styles.row}>
<h4>Filtering Options</h4>
<label className={styles.label}>Movies</label>
<input
id="name"
className={styles.checkbox}
type="checkbox"
required
/>
</div>
<div className={styles.row}>
<label className={styles.label}>TV Show</label>
<input id="name" className={styles.checkbox} type="checkbox" />
</div>
<hr className={styles.hr} />
{/* <div className={styles.row}>
<input
className={styles.input}
id="search"
type="input"
required
placeholder="Please enter title"
value={this.state.movies}
onChange={this.handMoviesChange}
/>
</div>
<div className={styles.row}>
<input
className={styles.input}
type="text"
list="genre"
placeholder="Please Choose Genre"
/>
<datalist id="genre">
<option className={styles.option}>scifi</option>
<option>Documentry</option>
</datalist>
</div>
<div className={styles.row}>
<input
className={styles.input}
id="name"
type="input"
placeholder="Season Input"
/>
</div> */}
<div className={styles.row}>
<label className={styles.label}>Netflix</label>
<input className={styles.checkbox} id="name" type="checkbox" />
</div>
<div className={styles.row}>
<label className={styles.label}>Amazon Prime</label>
<input className={styles.checkbox} id="name" type="checkbox" />
</div>
<div className={styles.row}>
<label className={styles.label}>Apple TV+</label>
<input
className={styles.checkbox}
id="name"
type="checkbox"
required
/>
</div>
<div className={styles.row}>
<label className={styles.label}>Showmax</label>
<input
className={styles.checkbox}
id="name"
type="checkbox"
required
/>
</div>
<div className={styles.row}>
<label className={styles.label}>DSTV</label>
<input
className={styles.checkbox}
id="name"
type="checkbox"
required
/>
</div>
<hr className={styles.hr} />
<label for="cars" className={styles.label}>
Select Year
</label>
<div className={styles.row}>
<select
name="cars"
id="cars"
data-toggle="dropdown"
className={styles.dropdown}
>
{/* <option value=""></option>
*/} <option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
</div>
<label for="cars" className={styles.label}>
Select Genre
</label>
<div className={styles.row}>
<select
name="cars"
id="cars"
data-toggle="dropdown"
className={styles.dropdown}
>
{/* <option value=""></option>
*/} <option value="SCIFI">SCIFI</option>
<option value="comedy">COMEDY</option>
<option value="ADVENTURE">ADVENTURE</option>
<option value="DOCUMENTRY">DOCUMENTRY</option>
</select>
</div>
<label for="cars" className={styles.label}>
Select Age Restriction
</label>
<div className={styles.row}>
<select
name="cars"
id="cars"
data-toggle="dropdown"
className={styles.dropdown}
>
{/* <option value=""></option>
*/} <option value="SCIFI">18+</option>
<option value="comedy">Adult</option>
<option value="ADVENTURE">Kids</option>
<option value="DOCUMENTRY">Cartoons</option>
</select>
</div>
<button className={styles.button} type="submit">
Apply Filters
</button>
</form>
</div>
<div className={styles.results}>
{/* here we are going to do conditional rendering like if netflix checkbox clicked then show or else not */}
{/* <img className={styles.condimg}
src={""}
alt="condren"
/> */}
<h4 className={styles.h2}>Search Results for {this.state.title}</h4>
{this.state.filteredShows.slice(0,4).map((filteredShows, index) => {
return (
<div>
<h1 className={styles.title}>{filteredShows.Title}</h1>
<img
className={styles.image}
src={filteredShows.Thumbnail}
alt="Thumbnail"
/>
<h5 className={styles.genre}>
{filteredShows.Genre} & {filteredShows["Release date"]}
</h5>
<p className={styles.desc}>{filteredShows.Description}</p>
</div>
);
})}
</div>
<Pagination/>
</div>
);
}
}
and output of the second component is like this
and can anyone help me for getting data from the first component to another second component I know we can do it with help of props and I am not getting how can I do that can anyone help me with this.
you can pass state through React router
<Link
to={{
pathname: '/pathname',
state: { results: 'this is results' }
}}
/>
In the component you can access the variable like this:
componentDidMount: function() {
var results= this.props.location.state.results
},
hope it help :D
You can add a prop (function) onUpdate to your search component, then call this function when you submit your search. On the parent-component, you can then add logic to pass it to your other component. For example, you add it to a state, which is then passed to your second component.
handMoviesChange = (event) => {
this.setState({
movies: event.target.value,
});
this.props.onUpdate(event.target.value);
};
Then in your parent component:
<example onUpdate={(movies) => setState({ movies })} />
<searchtest movies={this.state.movies} />
Hope it helps.

redux-form initialValues

I kinda getting lost here while i try to populate a redux-form V6.
I'm trying to create a contact form with person and company details. Since I'm new to the react universe I jump from one Doc/Tutorial to the other... So it may looks a bit scraped together.
I don't understand the concept how I can tell the Form that it has
to submit a ID that is comming from "props.match.params.id".? Or is
it just a bind and will get the result when i call this.props.dispatch(getContact(this.props.match.params.id)); in the Contact Component?
The reducer returns a Object that has the Person and Company as
"sub"-Object how can i match that to the Form?
Is there a way to debug the Form? I just see that my request returned a contact but i don't know if it even reaches the Form.
I use react-router to link to:
/contacts/contact/:id -> Populated Contact Form
Because of the redux/routerv4 issues i have to wrap my React.Component in withRouter to get the params in props. I don't know how i can connect withRouter and mapDispatchToProps, So my Contact Component looks as follows:
import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { FormattedMessage } from 'react-intl';
import {getContact} from "../../../Actions/contactsActions";
import ContactForm from './Forms/ContactForm';
#connect((store) => {
return {
contacts: store.contacts,
countries: store.countries,
contactCategories: store.contactCategories
}
})
class Contact extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {},
};
}
componentWillMount() {
if(this.props.match.params.id) {
this.props.dispatch(getContact(this.props.match.params.id));
}
}
handleSubmit(data) {
console.log(data);
}
render() {
return (
<div className="contact-container">
<ContactForm onSubmit={this.handleSubmit} />
</div>
)
}
}
export default withRouter(Contact);
And the Form looks like:
import React from 'react'
import { connect } from 'react-redux'
import { Field, reduxForm, formValueSelector } from 'redux-form'
import { FormattedMessage } from 'react-intl';
import {getContact} from "../../../../Actions/contactsActions";
class ContactForm extends React.Component {
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit}>
<div className="tab-pane fade show active" id="general" role="tabpanel" aria-labelledby="general-tab">
<div className="row">
<div className="col-lg-6 col-6">
<h2>
<FormattedMessage id={ 'Company' } values={{name:"Company"}} />
</h2>
<div className="form-group row">
<label htmlFor="company-name" className="col-4 col-form-label">
<FormattedMessage id={ 'Companyname' } values={{name:"Company name"}} />
</label>
<div className="col-8">
<Field component="input" className="form-control" name="company-name" placeholder="Company name" />
</div>
</div>
<div className="form-group row">
<label htmlFor="other-name" className="col-4 col-form-label">
<FormattedMessage id={ 'Othername' } values={{name:"Other name"}} />
</label>
<div className="col-8">
<Field component="input" className="form-control" name="other-name" placeholder="In case of sister company/group"/>
</div>
</div>
</div>
<div className="col-lg-6 col-6">
<h2>
<FormattedMessage id={ 'Person ' } values={{name:"Person"}} />
</h2>
<div className="form-group row">
<label htmlFor="person-language" className="col-4 col-form-label">
<FormattedMessage id={ 'Language' } values={{name:"Language"}} />
</label>
<div className="col-8">
<Field component="select" className="form-control" name="person-language" />
</div>
</div>
<div className="form-group row">
<label htmlFor="person-gender" className="col-4 col-form-label">
<FormattedMessage id={ 'Gender' } values={{name:"Gender"}} />
</label>
<div className="col-8">
<Field component="select" className="form-control" name="person-gender">
</Field>
</div>
</div>
<div className="form-group row">
<label htmlFor="person-salutation" className="col-4 col-form-label">
<FormattedMessage id={ 'Salutation' } values={{name:"Salutation"}} />
</label>
<div className="col-8">
<Field component="select" className="form-control" name="person-salutation" />
</div>
</div>
<div className="form-group row">
<label htmlFor="person-title" className="col-4 col-form-label">
<FormattedMessage id={ 'Title' } values={{name:"Title"}} />
</label>
<div className="col-8">
<Field component="input" className="form-control" name="person-title" placeholder="Prof. Dr. Dr."/>
</div>
</div>
<div className="form-group row">
<label htmlFor="first-name" className="col-4 col-form-label">
<FormattedMessage id={ 'First-name' } values={{name:"First name"}} />
</label>
<div className="col-8">
<Field component="input" className="form-control" name="first-name" placeholder="First name"/>
</div>
</div>
<div className="form-group row">
<label htmlFor="further-names" className="col-4 col-form-label">
<FormattedMessage id={ 'Further-names' } values={{name:"Further names"}} />
</label>
<div className="col-8">
<Field component="input" className="form-control" name="further-names" placeholder="Further names"/>
</div>
</div>
<div className="form-group row">
<label htmlFor="last-name" className="col-4 col-form-label">
<FormattedMessage id={ 'Last-name' } values={{name:"Last name"}} />
</label>
<div className="col-8">
<Field component="input" className="form-control" name="last-name" placeholder="Last name"/>
</div>
</div>
<div className="form-group row">
<label htmlFor="job-title" className="col-4 col-form-label">
<FormattedMessage id={ 'Job-title' } values={{name:"Job title"}} />
</label>
<div className="col-8">
<Field component="input" className="form-control" name="job-title" placeholder="Last name"/>
</div>
</div>
</div>
</div>
</div>
</form>
)
}
}
const validate = (values) => {
const errors = {};
if(!values.Companyname) {
errors.Companyname = "Enter a Companyname";
}
return errors;
};
ContactForm = reduxForm({
validate,
form: 'contact',
enableReinitialize : true
})(ContactForm);
ContactForm = connect(
state => ({
initialValues: state.contacts.contacts
}),
{ load: getContact }
)(ContactForm);
export default ContactForm;

Resources