For example, if I have a useState with the string "drama" set as its value, can I use the useState’s string in the path when accessing data in an object? So console.log(movies[0].drama) would be functionally the same as something like console.log(movies[0].--useStateName--).
Specifically I’ve got an array of movies with each movie having standard data such as title, release date, rating etc. but each movie also has a data point for every possible genre as a boolean, 0 if it is that genre, 1 if it is not.
If I’m trying to console log if the first movie in the array is a drama, I can console.log(movies[0].drama) and it will give ‘1’, because the movie it’s returning is a drama.
Separately from the API, I have an array in the application made up of just the genres as an array of strings, this array has been mapped to a form select input. A useState is being updated with whichever genre is selected in the select input.
So the problem is that I need to be able to use the string saved in the useState when checking for movies that belong to whichever genre is in the useState at the time. So if the useState is the string "drama", I need to be able to do something like console.log(movies[0].<useStateName>) and have it do the exact same thing as console.log(movies[0].drama).
>Solution :
In React, you cannot directly use a string stored in a useState hook to access properties in an object, as the state value is not automatically evaluated as a variable. However, you can achieve a similar result by using square bracket notation to access the object property dynamically.
Here’s an example of how you can use the string stored in a useState hook to access properties in an object:
import React, { useState } from "react";
const MovieComponent = () => {
const [selectedGenre, setSelectedGenre] = useState("drama");
const movies = [
{
title: "Movie 1",
drama: 0,
action: 1,
romance: 0
},
{
title: "Movie 2",
drama: 1,
action: 0,
romance: 1
},
{
title: "Movie 3",
drama: 1,
action: 1,
romance: 0
}
];
// Accessing movie genre dynamically using useState value
const isGenre = movies[0][selectedGenre] === 0 ? "Yes" : "No";
return (
<div>
<h1>Movie Details</h1>
<p>Genre: {selectedGenre}</p>
<p>Is it a {selectedGenre} movie? {isGenre}</p>
<select
value={selectedGenre}
onChange={(e) => setSelectedGenre(e.target.value)}
>
<option value="drama">Drama</option>
<option value="action">Action</option>
<option value="romance">Romance</option>
</select>
</div>
);
};
export default MovieComponent;
In the above example, selectedGenre is the useState hook that stores the selected genre as a string. The movies array contains movie objects with properties for different genres, where 0 represents the genre is present and 1 represents the genre is not present. By using movies[0][selectedGenre], we can access the genre property dynamically based on the value stored in the selectedGenre state, which allows us to retrieve the correct genre data from the movie object.