How can I access key using value in ReactJs? - javascript

I'm following a reactJS tutorial from Udemy and I was trying something on my own.
Project:
This is a simple project where I can add or remove goals
What I want to add extra is I want to clear the input text field when clicked on submit(Add goal) button. And I am able to do it but I think there is one problem.
The Whole Code
import React, { useState } from "react";
import Button from "../../UI/Button/Button";
import style from "./CourseInput.module.css";
const CourseInput = (props) => {
const [enteredValue, setEnteredValue] = useState("");
const [isValid, setIsValid] = useState(true);
const goalInputChangeHandler = (event) => {
setEnteredValue(event.target.value);
if (enteredValue.trim().length > 0) {
setIsValid(true);
}
console.log("=>" + enteredValue);
};
const formSubmitHandler = (event) => {
event.preventDefault();
if (enteredValue.trim().length === 0) {
setIsValid(false);
return;
}
props.onAddGoal(enteredValue);
// empty the inputbar and reset state (enteredValue)
console.log(event);
event.target[0].value = ""; // the main
setEnteredValue(""); // two lines.
};
return (
<form onSubmit={formSubmitHandler}>
<div className={`${style["form-control"]} ${!isValid && style.invalid}`}>
<label>Course Goal</label>
<input type="text" onChange={goalInputChangeHandler} />
</div>
<Button type="submit">Add Goal</Button>
</form>
);
};
export default CourseInput;
as you can see in above code I'm accessing input field through form events.
I accessed the input field through index number which I think is hard coded. In future if number of form element increases/decreases there is a chance that index number might change. so what I want to do is access the input value without using index. Is that possible?(I know it is), and how do I do it?

If you are working with a form's onSubmit action and have the onSubmit event then you can reset the form directly.
const formSubmitHandler = (event) => {
event.preventDefault();
if (enteredValue.trim().length === 0) {
setIsValid(false);
return;
}
props.onAddGoal(enteredValue);
setEnteredValue("");
event.target.reset(); // <-- calls form's reset action
};
const CourseInput = (props) => {
const [enteredValue, setEnteredValue] = React.useState("");
const [isValid, setIsValid] = React.useState(true);
const goalInputChangeHandler = (event) => {
setEnteredValue(event.target.value);
if (enteredValue.trim().length > 0) {
setIsValid(true);
}
};
const formSubmitHandler = (event) => {
event.preventDefault();
if (!enteredValue.trim().length) {
setIsValid(false);
return;
}
props.onAddGoal(enteredValue);
setEnteredValue("");
event.target.reset();
};
return (
<form onSubmit={formSubmitHandler}>
<div>
<label>Course Goal</label>
<input type="text" onChange={goalInputChangeHandler} />
</div>
<button type="submit">Add Goal</button>
</form>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(
<CourseInput onAddGoal={(val) => console.log(val)} />,
rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />

You may use Refs in order to achieve this:
function MyComponent() {
const textInput = React.useRef(null);
const formSubmitHandler = (event) => {
event.preventDefault();
if (enteredValue.trim().length === 0) {
setIsValid(false);
return;
}
props.onAddGoal(enteredValue);
// empty the inputbar and reset state (enteredValue)
console.log(event);
textInput.current.value = "";
};
// other code
return <input type="text" onChange= {goalInputChangeHandler} ref={textInput} />
}

It's enough to add value={enteredValue} to input field and set it to empty string after submit the form.
Also if you have any other input field, you can try event.target.reset().
So try this:
import React, { useState } from "react";
// import styled from "styled-components";
import Button from "../../UI/Button/Button";
import style from "./CourseInput.module.css";
const CourseInput = (props) => {
const [enteredValue, setEnteredValue] = useState("");
const [isValid, setIsValid] = useState(true);
const goalInputChangeHandler = (event) => {
setEnteredValue(event.target.value);
if (enteredValue.trim().length > 0) {
setIsValid(true);
}
console.log("=>" + enteredValue);
};
const formSubmitHandler = (event) => {
event.preventDefault();
if (enteredValue.trim().length === 0) {
setIsValid(false);
return;
}
props.onAddGoal(enteredValue);
// empty the inputbar and reset state (enteredValue)
setEnteredValue("");
event.target.reset();
};
return (
<form onSubmit={formSubmitHandler}>
<div className={`${style["form-control"]} ${!isValid && style.invalid}`}>
<label>Course Goal</label>
<input type="text" value={enteredValue} onChange={goalInputChangeHandler} />
</div>
<Button type="submit">Add Goal</Button>
</form>
);
};
export default CourseInput;

Related

How to turn a handleSubmit form function into a reusable one

I'm using the React-Bootstrap handleSubmit function to validate a form , submit it , and at the same time call sign() to register my user.
Since I will be using a similar form to login the user (just changing the function that gets called inside), and probably in more views, I would like to "outsource" this function, turn it into a reusable one, put in a different file, and call it when needed, passing the arguments required , to make my code cleaner and less repetitive. But I am quite lost about where to start and how I should do it.
Any help is much appreciated.
In my SignUp.jsx component :
import { useState, useContext } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";
function SignUp() {
const [validated, setValidated] = useState(false);
const handleSubmit = (e) => {
const form = e.currentTarget;
console.log(form);
if (form.checkValidity() === false) {
e.preventDefault();
e.stopPropagation();
}
setValidated(true);
if (form.checkValidity() === true) {
e.preventDefault();
sign();
}
};
const sign = () => {
console.log("user signed up");
}
const handleChangeHandler = (e) => {
setNewUser({ ...newUser, [e.target.name]: e.target.value });
};
// I omitted many Form fields to reduce the code
return (
<div className="containerSignUp">
<div className="innerContainerSignUp">
<h1>Sign Up</h1>
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Row>
<Col>
<Form.Group className="mb-3" controlId="formBasicUserName">
<Form.Label>Username</Form.Label>
<Form.Control
required
name="userName"
value={newUser.userName ? newUser.userName : ""}
type="text"
onChange={handleChangeHandler}
/>
<Form.Control.Feedback type="invalid">
Please pick a user name.
</Form.Control.Feedback>
</Form.Group>
</Col>
</Row>
<Button type="submit" className="signButton">
Signup
</Button>
</Form>
</div>
</div>
);
}
export default SignUp;
My attempt :
I created a file validateForm.js :
const handleSubmit = (event, func) => {
// const [validated, setValidated] = useState(false); // I cannot use a state outside a react component.
const form = e.currentTarget;
console.log("form", form);
if (form.checkValidity() === false) {
e.preventDefault();
e.stopPropagation();
}
setValidated(true);
if (form.checkValidity() === true) {
e.preventDefault();
func();
}
};
export { handleSubmit };
In signUp.jsx I import it, and call it :
import { handleSubmit } from "../utils/validateForm";
And call it when I submit the form :
<Form noValidate validated={validated}
onSubmit={(e) => {
handleSubmit(e, sign, setValidated(true));}}>
You can achieve this using a custom hook:
useHandleSubmit.js
const useHandleSubmit() {
const [validated, setValidated] = useState(false);
const handleSubmit = (event, func) => {
const form = event.currentTarget;
console.log("form", form);
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
// maybe you must move this inside the next `if`, otherwise move it to the end
setValidated(true);
if (form.checkValidity() === true) {
event.preventDefault();
func();
}
};
return { handleSubmit, validated };
}
export default useHandleSubmit;
In signUp.jsx:
import useHandleSubmit from '../utils/useHandleSubmit';
...
const { handleSubmit, validated } = useHandleSubmit();
...
<Form noValidate validated={validated}
onSubmit={(e) => {
handleSubmit(e, sign}}>

React form how to get user data based on a toggle on/off

I have a form in React JS with one toggle/switch. If toggle/switch is on, then two inputs appear in the screen. So i want to get user data if the user types in inputs and the toggle/switch is on and stays on. So if the user types in inputs but he toggles/switches again to off then input values get reset and when he saves the form i must get empty user data(i get the initial values). How can i achieve something like this? I'm checking in submit handler if the switch button is false and im setting the usestate to the initial values, but it doesnt work.
My code:
Form.js
import React, { useRef, useState } from "react";
import Wrapper from "./UI/Wrapper";
import Switch from '#mui/material/Switch';
import "./Form.css";
const Form = () => {
const [showCertification, setShowCertification] = useState(false);
const [enteredCodecert, setEnteredCodecert] = useState('');
const codecertRef = useRef();
const [codesteps, setCodesteps] = useState([{ value: null }]);
const codestepsRef = useRef();
const enteredCodecertIsValid = showCertification && enteredCodecert.trim() !== '';
const codecertInputIsInvalid = !enteredCodecertIsValid;
const codestepsIsValid = showCertification && codesteps.length >= 1 && codesteps.every(codestep => codestep.value !== null && codestep.value.trim() !== '');
const codestepInputIsInvalid = !codestepsIsValid;
const showCertificationHandler = (event) => {
setShowCertification(prevState => !prevState);
if (!showCertification) {
setEnteredCodecert('');
setCodesteps([{value: null}]);
}
}
const codecertChangeHandler = (event) => {
setEnteredCodecert(event.target.value);
}
const stepChangeHandler = (i, event) => {
const values = [...codesteps];
values[i].value = event.target.value;
setCodesteps(values);
}
const addStepHandler = (event) => {
event.preventDefault();
const values = [...codesteps];
values.push({ value: null });
setCodesteps(values);
}
const removeStepHandler = (i, event) => {
event.preventDefault();
const values = [...codesteps];
values.splice(i, 1);
setCodesteps(values);
}
const submitHandler = (event) => {
event.preventDefault();
if (!enteredCodecertIsValid && showCertification) {
codecertRef.current.focus();
return;
}
if (!codestepsIsValid && showCertification) {
if (codesteps.length >= 1) {
codestepsRef.current.focus();
return;
}
return;
}
if (showCertification === false) {
setEnteredCodecert('');
setCodesteps([{value: null}]);
}
console.log(enteredCodecert);
console.log(codesteps);
}
return (
<Wrapper>
<form onSubmit={submitHandler}>
<fieldset className={`${(showCertification && codecertInputIsInvalid) || (showCertification && codestepInputIsInvalid) ? 'govgr-form-group__error' : '' }`}>
<legend><h3 className="govgr-heading-m">Certifications</h3></legend>
<Switch id="certification" checked={showCertification} onClick={showCertificationHandler} inputProps={{ 'aria-label': 'controlled' }} />
<label className="govgr-label govgr-!-font-weight-bold cert-label" htmlFor="certification">Certification</label>
{showCertification && (
<div>
<div className="govgr-form-group">
<label className="govgr-label govgr-!-font-weight-bold" htmlFor="codecert">Code Certification*</label>
{codecertInputIsInvalid && <p className="govgr-error-message"><span className="govgr-visually-hidden">Λάθος:</span>Code Certification is required.</p>}
<input className={`govgr-input govgr-!-width-three-quarter ${codecertInputIsInvalid ? 'govgr-error-input' : ''}`} id="codecert" name="codecert" type="text" value={enteredCodecert} ref={codecertRef} onChange={codecertChangeHandler} />
</div>
<div className="govgr-form-group">
<label className="govgr-label govgr-!-font-weight-bold" htmlFor="codestep">Code STEPS*</label>
{codestepInputIsInvalid && <p className="govgr-error-message"><span className="govgr-visually-hidden">Λάθος:</span>Code STEPS are required.</p>}
{codesteps.map((field, idx) => {
return (
<div key={`${field}-${idx}`}>
<div className="flex-row">
<input className={`govgr-input govgr-input--width-10 input-step ${codestepInputIsInvalid ? 'govgr-error-input' : ''}`} id="codestep" type="text" ref={codestepsRef} value={field.value || ""} onChange={e => stepChangeHandler(idx, e)} />
<button className="govgr-btn govgr-btn-warning remove-step" onClick={(e) => removeStepHandler(idx, e)}>Χ</button>
</div>
</div>
);
})}
<button className="govgr-btn govgr-btn-secondary button-step" onClick={addStepHandler}>Add Code Step</button>
</div>
</div>
)}
</fieldset>
<button className="govgr-btn govgr-btn-primary btn-center" type="submit">Save</button>
</form>
</Wrapper>
);
};
export default Form;
The issue is that in showCertificationHandler when you toggle the showCertification you are expecting the state update to be immediate.
const showCertificationHandler = (event) => {
setShowCertification(prevState => !prevState);
if (!showCertification) {
setEnteredCodecert('');
setCodesteps([{value: null}]);
}
}
This is not the case with React state updates, however. React state updates are enqueued and asynchronously processed.
To resolve, move the "reset" logic into an useEffect hook with a dependency on the showCertification state.
const showCertificationHandler = () => {
setShowCertification((prevState) => !prevState);
};
useEffect(() => {
if (!showCertification) {
setEnteredCodecert("");
setCodesteps([{ value: null }]);
}
}, [showCertification]);
For the same reason above, when resetting the states in your submitHandler they are enqueued and asynchronously processed, so console logging the state immediately after will only ever log the state values from the current render cycle, not what they will be on a subsequent render cycle. You can remove the "reset" logic from submitHandler.
const submitHandler = (event) => {
event.preventDefault();
if (!enteredCodecertIsValid && showCertification) {
codecertRef.current.focus();
return;
}
if (!codestepsIsValid && showCertification) {
if (codesteps.length >= 1) {
codestepsRef.current.focus();
return;
}
return;
}
console.log({enteredCodecert, codesteps});
};

How to get each user's keystroke when he pressed a certain key?

I need to get each user's keystroke when he pressed a certain key("#") and stop getting his keystroke when he pressed other key(space(" ")). For example: a user enters the text "I wanna go to #shop", I need to save his input and the tag inside it. How can I do it? I wrote some code to do it but I don't know how to make it completely
onKeyDown = (e) => {
let value = e.target.value, tags = [], currentTag = "";
if (e.key == "Enter") {
this.setState((state) => {
const item = this.createNote(value, tags);
return { notes: [...state.notes, item] };
});
}
if (e.key == "#") {}
};
You can make use of regex /#[^\s]+/g
Live Demo
export default function App() {
const [value, setValue] = useState("");
const [tags, setTags] = useState([]);
function onInputChange(e) {
const value = e.target.value;
setValue(value);
const tags = value.match(/#[^\s]+/g) ?? [];
setTags(tags);
}
return (
<>
<input type="text" name="" value={value} onChange={onInputChange} />
<ul>
{tags.map((tag) => {
return <li key={tag}> {tag} </li>;
})}
</ul>
</>
);
}
EDITED: You can make use of useMemo hook as
Thanks to 3limin4t0r
Live Demo
export default function App() {
const [value, setValue] = useState("");
const tags = useMemo(() => value.match(/#\S+/g) || [], [value]);
function onInputChange(e) {
const value = e.target.value;
setValue(value);
}
return (
<>
<input type="text" name="" value={value} onChange={onInputChange} />
<ul>
{tags.map((tag) => {
return <li key={tag}> {tag} </li>;
})}
</ul>
</>
);
}
Instead of parsing individual key values, you can use a function like this to parse your input field on changes and return an array of hashtags (without the leading #):
TS Playground link
function parseTags (input: string): string[] {
return (input.match(/(?:^#|[\s]#)[^\s]+/gu) ?? []).map(s => s.trim().slice(1));
}
Here's a working example in a functional component which incorporates the function:
<script src="https://unpkg.com/react#17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#17.0.2/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/#babel/standalone#7.16.4/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel" data-type="module" data-presets="react">
const {useState} = React;
function parseTags (input) {
return (input.match(/(?:^#|[\s]#)[^\s]+/gu) ?? []).map(s => s.trim().slice(1));
}
function Example () {
const [value, setValue] = useState('');
const [tags, setTags] = useState([]);
const handleChange = (ev) => {
const {value} = ev.target;
setValue(value);
setTags(parseTags(value));
};
return (
<div>
<input
type="text"
onChange={handleChange}
placeholder="Type here"
value={value}
/>
<div>Parsed tags:</div>
<ol>
{tags.map((str, index) => <li key={`${index}.${str}`}>{str}</li>)}
</ol>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('root'));
</script>
Something like this should work for you; You can adapt if you don't have access to hooks:
const RecorderInput = ({ onChange }) => {
const [isRecording, setIsRecording] = useState(false);
const toggleRecording = (e) => {
const character = String.fromCharCode(e.charCode);
if (character === '#') {
setIsRecording(true);
}
if (character === ' ') {
setIsRecording(false);
}
}
const handleChange = (e) => {
if (isRecording) onChange(e);
toggleRecording(e);
}
<input type="text" onChange={handleChange} />
}
As other suggested your onChange can also use regex groups to capture hashes as the user types. Thinking about this now, it would probably be a lot cleaner to do it this way but regex is well documented so I won't go through the hassle

how to conditionally render the respond from an api

I want to get input from a user and compare it with the response I am getting from API, and conditionally render the information if it match or just show a sorry message,(the API only contain 1 set of a data object including 4 value) let me know what am I missing.
here is my code
import React, { useState } from "react";
import axios from "axios";
function Form() {
const [vatInput, setVatInput] = useState("");
const [responseVatState, setResponseVatState] = useState("");
const [responseCountryCodeState, setResponseCountryCodeState] = useState("");
const [result, setResult] = useState(false);
const handelVatState = (event) => {
setVatInput(event.target.value);
};
const closeModalHandler = () => {
setResult(false);
};
const onFormSubmit = (event) => {
event.preventDefault();
axios
.get("Some URL")
.then((response) => {
setResponseVatState(response.data.response.data.VATNumber);
setResponseCountryCodeState(response.data.CountryCode);
})
.catch((error) => {
console.log(error);
});
};
const inputCountryCode = vatInput.substring(0, 2);
const inputVatCode = vatInput.substring(2);
if (
inputCountryCode === responseCountryCodeState &&
inputVatCode === responseVatState
) {
setResult(true);
} else {
setResult(false);
}
return (
<div >
<h4>VAT Validator</h4>
<form onSubmit={onFormSubmit}>
<label className="text-muted">Please Enter A Vat Number:</label>
<input
type="text"
name="VatInput"
placeholder="Please Enter A Vat Number"
onChange={handelVatState}
/>
<br />
<input type="submit" value="Let'Go" />
</form>
<label className="text-muted">Result : </label>
{result ? (
<div>{vatInput}</div>
) : (
<div clicked={closeModalHandler}>
<span> Sorry !!! Please Insert corect VAT Number</span>
</div>
)}
</div>
);
}
export default Form;
and the error is
react-dom.development.js:14997 Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
so I get the input from the user and set it with hooks, then with Axios call get my data, then I split the string with
const inputCountryCode = vatInput.substring(0, 2);
const inputVatCode = vatInput.substring(2);
to compare with the input I have, if it's the same then render the data if not just render the sorry message
You have a couple of issues, the main of which resulting in Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. is due to an infinite loop of component re-rendering, which you force by setting state directly in the function body.
More specifically, this code:
if (
inputCountryCode === responseCountryCodeState &&
inputVatCode === responseVatState
) {
setResult(true);
} else {
setResult(false);
}
force react to re-evaluate the component because you're changing its state by using setResult. When react starts rendering the new body it yet again encounters setResult which results in a new update and re-render which, as you see, leads to a never-ending loop.
Furthermore, you don't need to save the request response to the component state at all, as it is relevant just for the calculation, which is needed only in the form submit handler itself. So, you should ditch the
const [responseVatState, setResponseVatState] = useState("");
const [responseCountryCodeState, setResponseCountryCodeState] = useState("");
state variables altogether. The only state you need except the input value is the validation result.
Also, you have a typo: setResponseVatState(response.data.response.data.VATNumber); should be setResponseVatState(response.data.VATNumber);.
Try this:
import React, { useState } from "react";
import axios from "axios";
function Form() {
const [vatValue, setVatValue] = useState("");
const [isVatValid, setIsVatValid] = useState(false);
const handelVatState = (event) => {
setVatValue(event.target.value);
};
const closeModalHandler = () => {
setIsVatValid(false);
};
const onFormSubmit = (event) => {
event.preventDefault();
axios
.get("[URL]")
.then((response) => {
const inputCountryCode = vatValue.substring(0, 2);
const inputVatCode = vatValue.substring(2);
const { VATNumber, CountryCode } = response.data;
if (inputCountryCode === CountryCode && inputVatCode === VATNumber) {
setIsVatValid(true);
}
else {
setIsVatValid(false);
}
})
.catch((error) => {
console.log(error);
});
};
return (
<div >
<h4>VAT Validator</h4>
<form onSubmit={onFormSubmit}>
<label className="text-muted">Please Enter A Vat Number:</label>
<input
type="text"
name="VatInput"
placeholder="Please Enter A Vat Number"
onChange={handelVatState}
/>
<br />
<input type="submit" value="Let'Go" />
</form>
<label className="text-muted">Result : </label>
{isVatValid ? (
<div>{vatValue}</div>
) : (
<div clicked={closeModalHandler}>
<span> Sorry !!! Please Insert corect VAT Number</span>
</div>
)}
</div>
);
}
export default Form;
Also, I suppose <div clicked={closeModalHandler}> should be <div onClick={closeModalHandler}>?
EDIT:
Here is your solution after comments:
import React, { useState } from "react";
import axios from "axios";
function Form() {
const [vatValue, setVatValue] = useState("");
const [isVatValid, setIsVatValid] = useState(null);
const handelVatState = (event) => {
setVatValue(event.target.value);
};
const closeModalHandler = () => {
setIsVatValid(null);
};
const onFormSubmit = (event) => {
event.preventDefault();
axios
.get("https://vat.erply.com/numbers?vatNumber=BG999999999")
.then((response) => {
const inputCountryCode = vatValue.substring(0, 2);
const inputVatCode = vatValue.substring(2);
const { VATNumber, CountryCode } = response.data;
if (inputCountryCode === CountryCode && inputVatCode === VATNumber) {
setIsVatValid(true);
}
else {
setIsVatValid(false);
}
})
.catch((error) => {
console.log(error);
});
};
const getResultRepresentation = () => {
if (isVatValid === null) {
return null;
}
if (isVatValid) {
return (
<>
<label className="text-muted">Result: </label>
<div>{vatValue}</div>
</>
);
}
else {
return (
<div onClick={closeModalHandler}>
<span> Sorry !!! Please Insert corect VAT Number</span>
</div>
);
}
}
return (
<div >
<h4>VAT Validator</h4>
<form onSubmit={onFormSubmit}>
<label className="text-muted">Please Enter A Vat Number:</label>
<input
type="text"
name="VatInput"
placeholder="Please Enter A Vat Number"
value={vatValue} // <= missing
onChange={handelVatState}
/>
<br />
<input type="submit" value="Let'Go" />
</form>
{getResultRepresentation()}
</div>
);
}
export default Form;
And here is a CodeSandbox to test it out.

Button handler to show preview

Iam doing one of the react assignment and I am stuck on the last part of this assignment. The question is like this: Improve on the application in the previous exercise, such that when the names of multiple countries are shown on the page there is a button next to the name of the country, which when pressed shows the view for that country. Here is my code. I tried some functions but couldnot get it so I wonder if someone can help me to cope with this last part..Thank you
import React, { useState, useEffect } from "react";
import axios from "axios";
import ReactDOM from "react-dom";
const App = () => {
const [countries, setCountries] = useState([]);
const [filter, setFilter] = useState("");
const [select, setSelected] = useState([]);
//console.log(countries);
useEffect(() => {
axios.get("https://restcountries.eu/rest/v2/all").then((response) => {
setCountries(response.data);
});
}, []);
const searchHandler = (e) => {
setFilter(e.target.value);
//console.log(filter);
const selected_countries = countries.filter((item) => {
const letter_case=item.name.toLowerCase().includes(filter.toLowerCase())
return letter_case
});
setSelected(selected_countries);
};
const countryLanguages = (languages)=>
languages.map(language => <li key={language.name}>{language.name}</li>)
const showCountries = () => {
if (select.length === 0) {
return <div></div>
} else if (select.length > 10) {
return "Find the specific filter";
}
else if(select.length>1 && select.length<10){
return (select.map(country=>
<div key={country.alpha3code}>{country.name}
<button>Show</button>//this part
</div>)
)
}
else if(select.length===1){
return(
<div>
<h1>{select[0].name}</h1>
<div>capital {select[0].capital}</div>
<div>population {select[0].population}</div>
<h2>languages</h2>
<ul>{countryLanguages(select[0].languages)}</ul>
<img src={select[0].flag} width="100px"/>
<h2>Weather in {select[0].capital}</h2>
</div>
)
}
};
return (
<div>
<h1>Countries</h1>
find countries: <input value={filter} onChange={searchHandler} />
{showCountries()}
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
Create a separate component.
const SingleCountry = ({name}) => {
const [ showDetails, setShowDetails ] = useState(false);
const toggleDetails = () => setShowDetails(!showDetails); //toggles the variable true/false
return ( <div>
<button onClick={toggleDetails}>Show Details</button>
{ /* renders the <div> only if showDetails is true */ }
{ showDetails && <div>These are the details of the country {name}</div> }
</div>)
}
Edit your showCountries component to use the new component.
const showCountries = () => {
if (select.length === 0) {
return <div></div>
} else if (select.length > 10) {
return "Find the specific filter";
}
else if(select.length>1 && select.length<10){
return (select.map(country=> <SingleCountry key={country.alpha3code} name={country.name} />
)
}

Categories