Issue
I have an array (const second) which i'm using in select element, which shows numbers as dropdown {option.target}, my question: is there a way to check inside that map (which i'm using) if 'target' from 'second' array is equal to 'id' from 'first' array then drop down should show value of 'name' from first array and not numbers from 'second' array, so drop down should show kitchen, sauna ...
should i have another map inside that map ?
codesandbox: https://codesandbox.io/s/react-hook-form-array-fields-forked-x46672?file=/src/index.js
import React from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";
import "./styles.css";
function App() {
const first = [
{ id: 0, mode: "camera", name: "Home" },
{ id: 1, mode: "room", name: "Kitchen" },
{ id: 2, mode: "room", name: "Sauna" }
];
const second = [
{ id: 0, source: 0, target: 1 },
{ id: 1, source: 0, target: 2 }
];
return (
<div>
<select>
{second?.map((option) => (
<option>{option.target}</option>
))}{" "}
</select>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
English is not my mother language so there could be mistakes.
Solution
It can be achieved using .find()
, which returns the first element in an array that satisfies the provided testing function.
function App() {
const first = [
{ id: 0, mode: "camera", name: "Camera" },
{ id: 1, mode: "room", name: "Kitchen" },
{ id: 2, mode: "room", name: "Sauna" }
];
const second = [
{ id: 0, source: 0, target: 1 },
{ id: 1, source: 0, target: 2 }
];
return (
<div>
<select>
{second?.map((option) => (
<option>{first.find(({id}) => id === option.target).name}</option>
))}{" "}
</select>
</div>
);
}
Answered By - Ro Milton
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.