Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
Get string as a variable name

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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];
about 4 years ago · Juan Pablo Isaza Report

0

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 </>
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!