Is it possible to use dynamic props to get the nested value of Javascript object as below, because I am getting error with this. please suggest me any solution.
Component.
import Link from "next/link";
import { info } from "@/lib/info";
export default function Tip({ name }) {
return (
<div>
<div>
<header>
<p className="text-sky-400"> {info.${name}.title}</p>
</header>
<div>
<div className="max-w-80">
<p className="text-justify">{info.${name}.content}</p>
<Link
className="flex text-sky-700 pl-2 font-bold justify-end"
target="blank"
href={info.${name}.href}
>
Read more ...
</Link>
</div>
</div>
</div >
);
}
Using the component.
<Tip name="accruedinterest" />
Array
export const info = {
acrruedinterest: {
title: "accrued interest",
content:
"In finance, accrued interest is the interest on a bond or loan that has accumulated since the principal investment, or since the previous coupon payment if there has been one already.",
href: "https://en.wikipedia.org/wiki/Accrued_interest",
},
acrruedcosine: {
title: "inverse cosine",
content:
"The inverse trigonometric functions are the inverses of the sine, cosine, tangent, cotangent, secant, and cosecant functions, and are used to obtain an angle from any of the angle's trigonometric ratios.",
href: "https://en.wikipedia.org/wiki/Inverse_trigonometric_functions",
},
inversehyperbolic: {
title: "inverse hyperbolic",
content:
"In mathematics, the inverse hyperbolic functions are invers of the hyperbolic functions, analogous to the inverse circular functions. There are six in common use: inverse hyperbolic sine, inverse hyperbolic cosine, inverse hyperbolic tangent, inverse hyperbolic cosecant, inverse hyperbolic secant, and inverse hyperbolic cotangent.",
href: "https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions",
},
}
You can't use dot notation with template strings to access properties in a JavaScript object. Instead, you should use bracket notation like info[name]
to dynamically retrieve nested values.
Here's an updated version of your code:
<p className="text-sky-400">{info[name]?.title}</p>
Be sure to also pass the right key as a prop in the Tip Component. I believe you meant to type acrruedinterest
instead