Can't get a sprite animation running in Pixijs on React - json

I am trying to follow along with the Pixijs guide provided here:
https://pixijs.github.io/examples/#/demos/animatedsprite-demo.js
- and after a bit of digging here is the sheet they use for their texture mapper
https://github.com/pixijs/examples/blob/gh-pages/required/assets/mc.json
To get an example up of a simple animated sprite. The issue that I am having is that I am following along almost exactly and I am getting an error - I do not know what is causing the problem and I don't know how to proceed debugging on my own.
The example has:
var app = new PIXI.Application();
document.body.appendChild(app.view);
app.stop();
PIXI.loader
.add('spritesheet', 'required/assets/mc.json')
.load(onAssetsLoaded);
function onAssetsLoaded() {
// create an array to store the textures
var explosionTextures = [],
i;
for (i = 0; i < 26; i++) {
var texture = PIXI.Texture.fromFrame('Explosion_Sequence_A ' + (i+1) + '.png');
explosionTextures.push(texture);
}
Where I have:
componentDidMount(){
this.renderer = PIXI.autoDetectRenderer(1366, 768);
this.refs.gameCanvas.appendChild(this.renderer.view);
this.stage = new PIXI.Container();
this.stage.width = 400;
this.stage.height = 400;
console.log(littlemarioforwardwalkjson)
PIXI.loader
.add(littlemarioforwardwalkpng, littlemarioforwardwalkjson)
.load(()=>this.spriteLoaded());
// console.log(PIXI.utils.TextureCache);
}
spriteLoaded(){
console.log('yolo');
var frames = [];
var index = 0;
console.log('hello there sailor');
console.log(PIXI.utils.TextureCache)
for (var i = 0; i < 3; i++) {
index = i+46;
var texture = PIXI.Texture.fromFrame("mario_characters1_"+index+".png");
marioTextures.push(texture);
}
}
The error I am getting is:
Error: the frameId “mario_characters1_46.png” does not exist in the texture cache
This is frustrating as my texturepacker json file is displaying correctly:
{"frames": {
"mario_characters1_46.png":
{
"frame": {"x":0,"y":0,"w":12,"h":15},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":12,"h":15},
"sourceSize": {"w":12,"h":15},
"pivot": {"x":0.5,"y":0.5}
},
"mario_characters1_47.png":
{
"frame": {"x":12,"y":0,"w":11,"h":16},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":11,"h":16},
"sourceSize": {"w":11,"h":16},
"pivot": {"x":0.5,"y":0.5}
},
"mario_characters1_48.png":
{
"frame": {"x":23,"y":0,"w":15,"h":16},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":15,"h":16},
"sourceSize": {"w":15,"h":16},
"pivot": {"x":0.5,"y":0.5}
}},
"meta": {
"app": "http://www.codeandweb.com/texturepacker",
"version": "1.0",
"image": "littlemarioforwardwalk.png",
"format": "RGBA8888",
"size": {"w":38,"h":16},
"scale": "1",
"smartupdate": "$TexturePacker:SmartUpdate:ae9c1a55b9f5884f4a4c0182ea720ca9:80c341baf7877296bb8143f4c51a5998:383ea93646790c53db2201f0624e779e$"
}
}
If I console.log(PIXI.utils.TextureCache) I get:
{data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAQCAYAAAB6Hg0eAAAACXBIWXMAAAsTAAALEwEAmpwYAAABUUlEQVRIx6VVPZqFIAxM/DwE1+B1WL5j0NrucWxtPcYr106uwS2yxQobMWB0aVSciTP5QYRikTVU7mGI+BT3lIdXJCmIFqcRVeP1fHN9xXzvrP/dCws46wG/FryLK9cdXpduvkegBE7Xg9vJE02etLhy/y6vE52F5eCMP2txkrg7POSOJDc1UVe4YT72rzZ+4qGU0mpjsj7Q4p7GF13lrGwG1leEYQakyVMiZvf7+1qWWnH5MEi8QwY0ZSsxrY+k7NQ4tUnNzZ8CcIKmRBk/vsFtBtxmxFI5689ZGd85RjbHDJxKc3Xw1coiYfOE7YZaByyPP8yAfesDYllZXznrAez+Yv60h+Xi1CdriJe1KzMg/U74M4aIJxNM1NNfUbn6v4aNhylaoTExISKBIdg+pwaGcJ7IFeKhIlx8TbRqvCVxUqYlPMfVjhO1MM3SiP+PuB9QuQ5f9MhyUAAAAABJRU5ErkJggg==: Texture}
So it would seem that the error is saying that the Texture Cache is only seeing one image blob - however, calling Texture.fromFrame is how the example on the website says to get it to work, and I think I am reproducing the code very closely.
If anyone has any ideas please let me know.

It was not easy to find an example with React, if that can help someone.
import React from "react";
import KingHuman from "./img/kinghuman/Idle/Idle.png";
import KingHumanJson from "./img/kinghuman/Idle/Idle.json";
import * as PIXI from 'pixi.js';
import { Stage, Container, AnimatedSprite } from '#inlet/react-pixi';
const PixiGame = () => {
const willMount = useRef(true);
const [textures, setTextures] = useState([]);
const loadSpritesheet = () => {
const baseTexture = PIXI.BaseTexture.from(KingHuman);
const spritesheet = new PIXI.Spritesheet(baseTexture, KingHumanJson);
spritesheet.parse(() => {
setTextures( Object.keys(spritesheet.textures).map((t) => spritesheet.textures[t]));
});
}
// Hooks way to do ComponentWillMount
if (willMount.current) {
loadSpritesheet();
willMount.current = false;
}
return (
<Stage width={300} height={300} options={{ backgroundColor: 0xeef1f5 }}>
<Container position={[150, 150]}>
<AnimatedSprite
anchor={0.5}
textures={textures}
isPlaying={true}
initialFrame={0}
animationSpeed={0.1}
/>
</Container>
</Stage>
);
}
export default PixiGame;

Yes I also struggled to get information for react on this. Had a sprite sheet without a json and created a function to generate the frame data. Adding on to the other answer is my code snippet
import React, { useRef, useState } from "react";
import KingHuman from "../../assets/mc.png";
import * as PIXI from 'pixi.js';
import { Stage, Container, AnimatedSprite } from '#inlet/react-pixi';
const generateFrames = (animationWidth, animationHeight, rowSize, colSize, fileWidth, fileHeight, imageName) => {
let generated = {
"frames": {},
"meta": {
"app": "Splash Software Assessment",
"version": "1.0",
"image": imageName,
"format": "RGBA8888",
"size": { "w": fileWidth, "h": fileHeight },
"scale": "1",
"smartupdate": ""
}
};
for (let i = 0; i < rowSize; i++) {
for (let j = 0; j < colSize; j++) {
const px = animationWidth * i;
const py = animationHeight * j;
const image = `${imageName}${px}${py}.png`
generated.frames[image] = {
"frame": { "x": px, "y": py, "w": animationWidth, "h": animationHeight },
"rotated": false,
"trimmed": false,
"spriteSourceSize": { "x": px, "y": py, "w": animationWidth, "h": animationHeight },
"sourceSize": { "w": animationWidth, "h": animationHeight }
}
}
}
return generated;
};
const PixiGame = () => {
const willMount = useRef(true);
const [textures, setTextures] = useState([]);
const KingHumanJson = generateFrames(240, 240, 4, 8, 1024, 2048, "mc.png")
const loadSpritesheet = async () => {
const baseTexture = PIXI.BaseTexture.from(KingHuman);
const spritesheet = new PIXI.Spritesheet(baseTexture, KingHumanJson);
const textures = await spritesheet.parse();
setTextures(Object.keys(textures).map((t) => textures[t]));
}
// Hooks way to do ComponentWillMount
if (willMount.current) {
loadSpritesheet();
willMount.current = false;
}
return (
<Stage width={300} height={300} options={{ backgroundColor: 0xeef1f5 }}>
<Container position={[150, 150]}>
<AnimatedSprite
anchor={0.5}
textures={textures}
isPlaying={true}
initialFrame={0}
animationSpeed={0.1}
/>
</Container>
</Stage>
);
}
export default PixiGame;

Related

Why does react refuse to convert jsx to HTML component and just returns [object Object]?

Please find // the console log I am talking about in the below code.
This console log returns string So its not that I am passing object here. but even then react doesn't recognise the jsx and adds object Object in HTML.
Output I am getting is:
import React, { useEffect, useState } from "react";
function App() {
const [file, setFile] = useState();
useEffect(() => {
setFile(
JSON.parse(`{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}`)
);
}, []);
return (
<>
{/* <import file component> */}
<JsonViewer file={file} />
</>
);
}
function JsonViewer({ file }: any) {
const [fileContent, setFileContent] = useState<any>();
useEffect(() => {
if (file) {
setFileContent(getJsonData(file, ""));
}
}, [file]);
function getJsonData(data: any, idToAppend: string) {
let t: any = [];
if (data.length) {
console.log(data.length);
for (let i in data) {
let idToA = `${idToAppend}${i.toString()}`;
t.push(getJsonData(data[i], idToA))
}
}
else {
Object.entries(data).forEach(([key, value], i) => {
const idToA = `${idToAppend}${i.toString()}`;
if (typeof value === "object") {
let a: any = value
t.push(
<div key={i} id={idToA}>
<button
onClick={(e) => {
let ele = document.getElementById(idToA);
if (ele) {
ele.innerHTML += getJsonData(value, idToA);
}
}}
>
{key}
</button>
</div>
);
}
else {
// the console log I am talking about
console.log(typeof value);
t.push(
<div key={i}>
<div
id={idToA}
>
{key}:{value}
</div>
</div>
);
}
}
);
}
return t;
}
return (
<div>
{fileContent}
</div>
);
}
export default App;
The reason why you are getting objects is because the current procedure is creating nested t lists. You can see the output here: https://codesandbox.io/s/youthful-sunset-ru8ic?file=/src/Old.tsx
An alternative, working approach:
import React from "react";
const DATA = {
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
};
interface theDat {
data: {
short_name: string;
name: string;
icons: Icons[];
start_url: string;
display: string;
theme_color: string;
background_color: string;
};
};
type Icons = {
src: string;
sizes: string;
type: string;
};
const App = () => {
const JsonInterpreter: Function = ({data}: theDat) => {
let elements = [];
Object.keys(data).forEach((dat, i) => {
let value = data[dat];
console.log(`this: ${dat} ${typeof value}`)
if (typeof value === 'string') {
elements.push(
<p key={i}>{dat} {value}</p>
)
} else if (typeof value === 'object') {
elements.push(
<p key={i}>{dat}</p>
);
console.log(value);
let nested = [];
(value as []).forEach((d, j) => {
let keys = Object.keys(d);
if (['src', 'type', 'sizes'].every(e => keys.includes(e))) { /* typeguard for icons */
nested.push(
<p key={`n-${j}`}>{JSON.stringify(d)}</p>
);
};
})
elements.push(...nested);
};
});
return elements;
};
return (
<>
<JsonInterpreter data={DATA} />
</>
);
};
export default App;
Working CodeSandbox: https://codesandbox.io/s/youthful-sunset-ru8ic?file=/src/App.tsx:0-1789

render html file with script in react app

I have a html file with script tag and some link into it.
when i render it with html file it bring the result i mean a chart but when i render it in react js app wiht dangerouslySetInnerHTML it does not render and does not bring my chart.
this is my html code that i take it from backend(api)
const html = `<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0" />
<link
href="somelink"
rel="stylesheet"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="app-chart-container">
<canvas class="app-charts" id="line-chart-40197" dir="ltr"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script>
$(document).ready(function () {
$("[data-toggle='tooltip']").tooltip({ placement: "right" });
});
var ctx = document.getElementById("line-chart-40197");
if (ctx) {
ctx.height = 300;
var myChart = new Chart(ctx, {
type: "line",
data: {
labels: [
"92/3",
"92/6",
"92/9",
"92/12",
"93/3",
"93/6",
"93/9",
"93/12",
"94/3",
"94/6",
"94/9",
"94/12",
"95/3",
"95/6",
"95/9",
"95/12",
"96/3",
"96/6",
"96/9",
"96/12",
"97/3",
"97/6",
"97/9",
"97/12",
"98/3",
"98/6",
"98/9",
"98/12",
"99/3",
"99/6",
],
type: "line",
defaultFontFamily: "VazirFD",
datasets: [
{
label: "شرکت",
data: [
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"-262",
"-262",
"-262",
"-262",
"66793",
"70787",
"122463",
"591087",
"591088",
"597421",
"600635",
"614257",
"1304086",
"1320727",
"1352606",
"2830629",
"3016812",
"3042351",
"3126253",
],
backgroundColor: "transparent",
borderColor: "#9d0606",
borderWidth: 2,
pointStyle: "circle",
pointRadius: 3,
pointBorderColor: "transparent",
pointBackgroundColor: "#9d0606",
type: "line",
},
],
},
options: {
responsive: true,
tooltips: {
mode: "index",
titleFontSize: 12,
titleFontColor: "#000",
bodyFontColor: "#000",
backgroundColor: "#fff",
defaultFontFamily: "VazirFD",
titleFontFamily: "VazirFD",
bodyFontFamily: "VazirFD",
cornerRadius: 3,
intersect: true,
callbacks: {
label: function (tooltipItem, data) {
return (
data.datasets[tooltipItem.datasetIndex].label +
" : " +
tooltipItem.yLabel
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
);
},
},
},
legend: {
display: true,
rtl: true,
labels: {
usePointStyle: true,
fontFamily: "VazirFD",
},
},
scales: {
xAxes: [
{
stacked: false,
display: true,
gridLines: {
display: true,
drawBorder: false,
},
scaleLabel: {
display: true,
labelString: "سال مالی",
fontFamily: "VazirFD",
},
ticks: {
fontFamily: "VazirFD",
fontColor: "#9aa0ac",
minRotation: 90,
callback: function (value, index, values) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
},
},
},
],
yAxes: [
{
stacked: false,
display: true,
gridLines: {
display: true,
drawBorder: false,
},
scaleLabel: {
display: false,
labelString: "میلیون ریال",
fontFamily: "VazirFD",
},
ticks: {
margin: 20,
fontFamily: "VazirFD",
fontColor: "#9aa0ac",
minRotation: 0,
callback: function (value, index, values) {
var processValue = value;
if (value >= 1000 && value < 1000000) {
processValue = value / 1e3 + "K";
} else if (value >= 1000000 && value < 1000000000) {
processValue = value / 1e6 + "M";
} else if (value >= 1000000000) {
processValue = value / 1e9 + "B";
} else if (value < 0 && value <= -1000 && value > -1000000) {
processValue = value / 1e3 + "K";
} else if (
value < 0 &&
value <= -1000000 &&
value > -1000000000
) {
processValue = value / 1e6 + "M";
} else if (value < 0 && value <= -1000000000) {
processValue = value / 1e9 + "B";
}
return processValue
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
},
},
},
],
},
title: {
display: true,
text: "روند سودآوری TTM (میلیون ریال)",
fontFamily: "VazirFD",
},
},
});
}
</script>
this is my html file.
but i have a problem with render of that with react
when I compile this file with
this is my react component that i want to render that html code (my html code has some script tag )
import React from "react";
export default function Dashboard() {
return (
<div dangerouslySetInnerHTML={{__html: html }} />
)
}
i dont get my html file correctly.
and react does not render it.
when i open this file into .html file it works but in react does not render any thing.
how can i render this file in react please help me
I had to do this recently because an API I was consuming returns HTML content. You can use a library like html-to-react to parse the HTML for you and convert it to a React component that you can then use inside your React application. In my case, I created a component so that I can reuse this logic anywhere I need to display HTML content.
import { useMemo } from 'react';
import { Parser } from 'html-to-react';
const HTMLContent = (props) => {
const htmlToReactParser = useMemo(() => new Parser(), []);
const parsedHTML = htmlToReactParser.parse(props.html);
return <div className={styles['blog-html-content']}>{parsedHTML}</div>;
};

Cesium GeoJSON datasource polygon material is white despite an image is specified

I am not able to figure out a way to change the material of a polygon entity from a GeoJsonDataSource. I would like to apply an image.
Here is an example using a color because I don't know how to embed an image on the online sandcastle:
var viewer = new Cesium.Viewer("cesiumContainer");
const poly = {
"type": "FeatureCollection",
"name": "MyPolygon",
"crs": {"type": "name",
"properties": {
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
}},
"features": [
{"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[[ 10.746500009923748, 48.314700009648320, 500 ],
[ 10.747500009924019, 48.315700009648104, 500 ],
[ 10.747038310965864, 48.315905422444722, 550 ],
[ 10.746038315853207, 48.314905418639555, 550 ],
[ 10.746500009923748, 48.314700009648320, 500 ]]
]}}]};
const Promise0 = async () => {
try {
const dataSource = await Cesium.GeoJsonDataSource.load(poly, {
stroke: Cesium.Color.BLUE,
strokeWidth: 3
});
const Promise1 = async () => {
try {
const polygonalFrame = await viewer.dataSources.add(dataSource);
viewer.zoomTo(polygonalFrame);
const entities = polygonalFrame.entities.values;
for (var i = 0; i < entities.length; i++) {
const entity = entities[i];
entity.polygon.material = new Cesium.Material({
fabric : {
type : 'Color',
uniforms : {
color : new Cesium.Color(1.0, 0.0, 0.4, 0.5)
}
}
});
}
}
catch (err) {
console.log("Error: ", err);
}
};
Promise1();
}
catch (e) {
console.log("Error:", e);
}
};
Promise0();
The polygon remains yellow, which is the default color I think.
For the image material, I use this definition locally:
new Cesium.Material({
fabric : {
type : 'Image',
uniforms : {
image : './image.png'
}
}
});
I fixed it using this way of defining the PolygonGraphics' material in my entity:
new Cesium.ImageMaterialProperty({
image: './image.png',
alpha: 0.5
});
But I noticed that alpha blending doesn't work when I try to apply it on my whole image...

Looping over an object that is within a another object

So I was working on this name card generator app. https://jsonplaceholder.typicode.com/users is the source of my database.
Any idea how to loop through the address part? My code so far.
import React, {useState, useEffect} from 'react';
import Namecard from './namecard'
function App() {
const [identis, setIdenti]=useState([]);
useEffect(()=>{
getIdenti()
},[]
);
const getIdenti = async()=>{
const acquired = await fetch(`https://jsonplaceholder.typicode.com/users`)
const data = await acquired.json()
setIdenti(data)
}
return (
<div>
{identis.map(identi=>(
<Namecard
name={identi.name}
email={identi.email}
address={identi.address}
/>
))}
</div>
)}
export default App
I think maybe you're going for something along these lines. Just to at least answer the question - here is how you would loop through the address. And I'm guessing you're trying to build up a readable string or something...
var users = [
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
}
}
];
var addressStr = '';
for (var user of users) {
addressStr = '';
for (var key of Object.keys(user.address)) {
key !== 'geo' && (addressStr += user.address[key] + ' ');
}
console.log(addressStr);
}
instead of looping through address part, just build a separate Address component.
const Address = ({ street, suite, ... }) => <h1>Street: {street}</h1>
const Namecard = ({ name, ..., children }) => <div> Name: {name} <div>{children}</div></div> // where children is the Address component
<Namecard
name={identi.name}
email={identi.email}
>
<Address {...identi.address} />
</Namecard>

My React navigation is dynamic, warning : You should only render one navigator explicitly in your app

I'm struggling to make my dynamic navigation working in my react-native app.
Here is what I have on my AppNavigation.js :
import {
createDrawerNavigator,
createStackNavigator,
createSwitchNavigator, DrawerItems, SafeAreaView
} from 'react-navigation'
import LoginScreen from '../screens/LoginScreen'
import ProfileScreen from "../screens/ProfileScreen";
import TemplatesScreen from "../screens/TemplatesScreen";
import AuthLoadingScreen from "../screens/AuthLoadingScreen";
import React from "react";
import {Button, Icon} from "native-base";
import {ScrollView} from "react-native";
import NewFilmScreen from "../screens/NewFilmScreen";
import SettingsScreen from "../screens/SettingsScreen";
import LogoutScreen from "../screens/LogoutScreen";
import TemplateWorkflowContainer from "./TemplateWorkflowContainer";
const WorkflowContainer = createStackNavigator(
{
TemplateContainer: {
screen: TemplateWorkflowContainer
}
},
{
headerMode: 'none',
}
);
// drawer stack
const AppNavigation = createDrawerNavigator({
TemplatesScreen: {screen: TemplatesScreen},
NewFilm: {screen: NewFilmScreen},
ProfileScreen: {screen: ProfileScreen},
SettingsScreen: {screen: SettingsScreen},
LogoutScreen: {screen: LogoutScreen}
},
{
drawerBackgroundColor: '#ff4559',
// Default config for all screens
headerMode: 'none',
initialRouteName: 'TemplatesScreen',
contentOptions: {
activeTintColor: '#fff',
inactiveTintColor: '#fff',
itemsContainerStyle: {
marginVertical: 0,
},
itemStyle: {
flexDirection: 'row-reverse',
},
iconContainerStyle: {
opacity: 0.8,
}
},
contentComponent: props =>
<ScrollView>
<SafeAreaView forceInset={{top: 'always', horizontal: 'never'}}>
<Button transparent>
<Icon name='close' style={{fontSize: 40, color: 'white'}} onPress={() => {
props.navigation.closeDrawer()
}}/>
</Button>
<DrawerItems {...props} />
</SafeAreaView>
</ScrollView>
});
const WrapperStack = createStackNavigator({
AppDrawer: AppNavigation,
WorkflowContainer: WorkflowContainer
},
{
headerMode: 'none'
}
);
// Manifest of possible screens, when the user sign in the loginStack will be unmount to never logged out the user with
// the back button
const PrimaryNav = createSwitchNavigator({
AuthLoading: {screen: AuthLoadingScreen},
Auth: {screen: LoginScreen},
App: {screen: WrapperStack}
}, {
initialRouteName: 'AuthLoading'
});
export default PrimaryNav;
My drawer is fine. The problem is on the WorkflowContainer. This is a navigation like this :
import React, { Component } from "react";
import { createStackNavigator } from "react-navigation";
import TemplateWorkflowNavigator from "./TemplateWorkflowNavigator";
export default class TemplateWorkflowContainer extends Component {
constructor(props) {
super(props);
this.state = {
content: null
};
}
generateScreens = data => {
const stack = {};
stack["0"] = {
screen: TemplateWorkflowNavigator,
navigationOptions: () => ({
title: data.title,
gesturesEnabled: true
})
};
for (let i = 0; i < data.scenes.length; i++) {
let screenNumber = data.scenes[i].priority + 1;
stack[screenNumber] = {
screen: TemplateWorkflowNavigator,
navigationOptions: () => ({
title: data.scenes[i].name,
gesturesEnabled: true
})
};
}
return stack;
};
renderStackNavigo = aTemplate => {
const TemplateStackNavigor = createStackNavigator(
this.generateScreens(aTemplate), {headerMode: 'none'}
);
return <TemplateStackNavigor screenProps={aTemplate}/>;
};
render() {
return this.props.navigation.state.params.json && this.renderStackNavigo(this.props.navigation.state.params.json);
}
}
It's dynamic, throught the this.props.navigation.state.params.jsoni got back a JSON like this :
{
"id": 5,
"title": "toto",
"dolly": 74,
"name": "toto",
"conditions": [
{
"name": "Calm",
"desc": "test",
"priority": 0
}
],
"medias": [
{
"path": "a_path_here",
"mobile_path": "a_path_here",
"size": 80851,
"type": "preview"
}
],
"scenes": [
{
"name": "Intro",
"priority": 0,
"conditions": [
{
"name": "smile",
"desc": "test",
"priority": 0
}
],
"medias": [
{
"path": "a_path_here",
"mobile_path": "a_path_here",
"size": 80851,
"type": "preview"
}
],
"elements": [
{
"name": "Name",
"priority": 0,
"type": "text",
}
]
}
]
}
It's working when I call this
this.props.navigation.navigate("TemplateContainer", { json: path });
But I have this warning :
You should only render one navigator explicitly in your app, and other
navigators should by rendered by including them in that navigator.
I tried a lot of things, but I'm so new on react native, nothing worked.
How can I make this navigation works with no warning ? What changes do I have to apply ?
As my assumption, your TemplateWorkflowContainer will look like this
export default class TemplateWorkflowContainer extends Component {
static router = null;
...
renderStackNavigo = aTemplate => {
const TemplateStackNavigor = createStackNavigator(
this.generateScreens(aTemplate), {headerMode: 'none'}
);
TemplateWorkflowContainer.router = TemplateStackNavigor.router;
return <TemplateStackNavigor screenProps={aTemplate}/>;
};
...
}