Home > other >  Get string as a variable name
Get string as a variable name

Time:03-15

I have a "LessonFrame" component that imports content in the form of components from a number of files titled Lesson1, Lesson2, Lesson3 etc. The two components I'm importing from each of them are called steps and Content, and I can call them in the parent component using Lesson1.steps, Lesson3.Content etc.

But I want to be able to pass the parent component a lesson number, and then render the subcomponents from the right file based on that - so if I pass prop "2", I want to call steps and Content from Lesson2.

Here's the relevant part of my code:

import * as Lesson1 from "./Lesson1";
import * as Lesson2 from "./Lesson2";
import * as Lesson3 from "./Lesson3";

export const LessonFrame = ({lesson}) => {

  const steps = eval("Lesson"   lesson).steps
  const Content = eval("Lesson"   lesson).Content

As you can see, I've tried doing eval("Lesson" lesson), but that doesn't work - and when I try to console log it I get this error: ReferenceError: Lesson1 is not defined

If I just console.log "Lesson1", though, that does work fine.

So it seems that it is trying to find a variable called Lesson1, but for some reason it isn't working.

TLDR: I want to be able to use a variable generated from the word "Lesson" and a number passed to a component as a prop, like "Lesson1", "Lesson2" etc.

Any ideas?

CodePudding user response:

Why not just use an array:

import * as Lesson1 from "./Lesson1";
import * as Lesson2 from "./Lesson2";
import * as Lesson3 from "./Lesson3";

const lessons = [Lesson1, Lesson2, Lesson3];

export const LessonFrame = ({lesson}) => {

  const { steps, Content } = lessons[lesson - 1];

CodePudding user response:

If you want to render a lesson based on props passed. You can simply use **switch case ** as shown below :

import * as Lesson1 from "./Lesson1";
import * as Lesson2 from "./Lesson2";
import * as Lesson3 from "./Lesson3";

export const LessonFrame = ({lesson}) => {

  switch(lesson){
    case 1 :  return <Lesson1 />
    case 2 : return <Lesson2 />
    case 3 : return <Lesson3 />
    default : return <>No lesson found with this lessonNumber </>
  }
}
  • Related