Saf
Saf

Reputation: 318

is it possible to convert string to jsx component? React Native

I am trying to implement dynamic render of react-native-chart-kit where the chart type will be set in props.

I thought of making it this way

import { LineChart, BarChart, PieChart, ProgressChart, ContributionGraph, StackedBarChart} from 'react-native-chart-kit'

export function chart(props){
   return <{props.type} data={props.data} //props.type is one of the imported components
            width={Dimensions.get('screen').width}
            height={220}
            chartConfig={props.config}
            style={{
              marginVertical: 8,
              borderRadius: 16
            }} />
}

is there a way for something like this?

Upvotes: 1

Views: 717

Answers (1)

apokryfos
apokryfos

Reputation: 40653

If you had a simple string component (e.g. h1 or a) then you could assign it to a variable e.g.

export function chart(props){
   const Type = 'a';
   return <Type />; // React.createElement('a') should also work
}

In your case where you refer to a class however you might find it easier to import the entire library:

import * as ChartKit from 'react-native-chart-kit'

export function chart(props){
   if (ChartKit[props.type]) {
       const Type = ChartKit[props.type];
       return <Type data={props.data} //props.type is one of the imported components
            width={Dimensions.get('screen').width}
            height={220}
            chartConfig={props.config}
            style={{
              marginVertical: 8,
              borderRadius: 16
            }} />
   }
   return null; // Or throw an error

}

As far as I'm aware there's no simple way to get the class definition reference from a string (aside from doing an eval which is bad practice).

Upvotes: 1

Related Questions