Octavian Niculescu
Octavian Niculescu

Reputation: 1327

Accessing an object with dot notation using props

I'm trying to use React-DnD and I have this code:

import { useDrag } from "react-dnd";
import { ItemTypes } from "./Constants";

type DraggableGameAnswerProps = {
    type: string
}

function DraggableGameAnswer(props: DraggableGameAnswerProps)
{
    const [{ isDragging }, drag] = useDrag(() => ({
        type: ItemTypes.{props.type},
        collect: (monitor) => ({
          isDragging: !!monitor.isDragging()
        })
      }))
}

export default DraggableGameAnswer;

but the line

type: ItemTypes.{props.type}

doesn't work.

Constants.tsx

export const ItemTypes = {
    raspuns1: 'raspuns1',
    raspuns2: 'raspuns2',
    raspuns3: 'raspuns3',
    raspuns4: 'raspuns4'
}

In the parent component, I want to decide which of those 4 options I want to pass onto the children, and then send through the props raspuns1/raspuns2/raspuns3/raspuns4.

In the above code you can see my approach - I also tried with bracket notation, but it hasn't worked either.

Is it possible to access the data in the object ItemTypes this way?

Thanks.

Upvotes: 0

Views: 674

Answers (1)

Robert-Jan Kuyper
Robert-Jan Kuyper

Reputation: 3346

I geuss you look for: ItemTypes[prop.type]

Upvotes: 2

Related Questions