0

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.

1 Answer 1

4

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',
  },

});
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing answer it worked great for me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.