-1

I want to do is I want to import React-Native dynamic path.

example:

import Demo from `./screens/${path}`;

I found one method using lazy, but it also only working when initialize const variable like this

const demo = 'Path';

let componentPath = `../Screen/${demo}`;

const DynamicComponent = React.lazy(() =>
  import(componentPath)
    .then(module => ({ default: module.screen })),
);

I want to get path by async storage saved variable, not like hard code variable. When I hard code variable it works, but I could not get it from async storage. I have tried to find any method to do it.

2
  • I've done some Googling and searching on the site and what I've gathered so far is that what you are asking for just doesn't seem possible with current Javascript capabilities. In overly-simplistic terms it's that transpilers (Babel/etc) need to have a pretty good idea what is being imported, e.g. where it can find it. Can you take a step back and provide more detail about the bigger problem you are trying to solve for, e.g. what is the "business" use case you need to solve? Commented Apr 20, 2024 at 6:17
  • I have been developing product app for clients. it should be one app. identify base on the login by clients and it will be render specific component. that's the main idea Commented Apr 20, 2024 at 7:49

1 Answer 1

-1
const demo = 'Path'; // Your dynamic path variable

// Construct the path to your component
let componentPath = `../Screen/${demo}`;

// Dynamically requires the component using the constructed path
const DynamicComponent = require(componentPath).default;

// Render the dynamically imported component
<DynamicComponent />
Sign up to request clarification or add additional context in comments.

2 Comments

This answer could use some polishing and provide a bit of explanation what the issue is and how the code change solves the problem.
This code doesn't work for me. let componentPath = ../Screen/demo; like this code it works . let componentPath = ../Screen/${demo}; but when we doing like this it doesn't work. actually can't change dynamic value like this ${demo}

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.