Reputation: 291
I want to import JSON files dynamically based on certain condition. My Code is
import TXT1 from "../Assets/TTCS1.json";
import TXT2 from "../Assets/TTCS2.json";
export class Timetable extends Component {
state = {class: 1};
render() {
return this.state.class === 1 ? (
<View style={styles.container}>
<Text>{TXT1.S5}</Text>
</View>
) : (
<View style={styles.container}>
<Text>{TXT2.S5}</Text>
</View>
);
}
}
These JSON files are large and a particular user will mostly use only any one of the JSON file hence importing all is waste of resources. I found an answer here How can I conditionally import an ES6 module? the answer works fine with JS files, but with JSON files I am confused what is to be put in .then() function.
Upvotes: 0
Views: 2709
Reputation: 3621
you can use require.
Created expo snack :
https://snack.expo.io/BJRqgSnqr
import React, { Component } from 'react';
import { Text, View, StyleSheet, ScrollView } from 'react-native';
import * as Constants from 'expo-constants';
var TXT1='',TXT2='';
export default class App extends Component {
state={TXT1:'',TXT2:''}
componentDidMount=()=>
{
TXT1 = require('./assets/TXT1.json');
this.setState({TXT1});
}
render() {
return (
<View style={styles.container}>
<Text>{JSON.stringify(this.state.TXT1)}</Text>
<Text>{JSON.stringify(TXT2)}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
Upvotes: 4