xxxxxxxxxx
<html>
<head>
<meta charset="UTF-8" />
<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://cdn.jsdelivr.net/npm/@babel/standalone@7.14.6/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel" data-presets="env,react">
const { useState } = React;
function App() {
const countries = [
{ countryName: "Australia", capitalName: "Canberra" },
{ countryName: "England", capitalName: "London" },
{ countryName: "India", capitalName: "New Delhi" },
];
const [result, setResult] = useState("");
function myFunction() {
setResult(
countries.findIndex((country) => country.countryName === "India")
);
}
return (
<div className='container'>
<h3>React Js find index of object in array by key value</h3>
<button onClick={myFunction} className="btn btn-primary">
Find Index of India
</button>
<p>Get index of object in array by key value: {result}</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
}
h3 {
font-size: 1.5rem;
margin-bottom: 1rem;
}
.btn {
padding: 0.5rem 1rem;
font-size: 1rem;
border-radius: 0.25rem;
background-color: #007bff;
color: #fff;
border: none;
cursor: pointer;
}
.btn:hover {
background-color: #0056b3;
}
p {
margin-top: 1rem;
}
</style>
</body>
</html>