Wednesday 13 February 2019

How do I include Javascript code in the render function of a react native app?




I'm a React and React native noob so its probably going to be a very silly question but how can I use the 'for loop' inside the render function to include my components? This is what I did




render() {
return (

{ for (let i=0; i<20; i++)
{
//This is my component

}
}


);
}


but it threw an error, then someone suggested to include the code in a method and call it inside the render function so I did



createButtons() {
for (let i =0; i<20; i++){
;
}

}

render() {
return (

{this.createButtons()}


);
}



now I dont see errors but its just a blank screen. I know you can access props but Is the render function supposed to contain primarily only JSX code? Thanks in advance.


Answer



Jsx can contain expressions which return Components or arrays of components. In you case you need something that returns an array of components.



Sticking with the for loop:



createButtons() {
let buttons = [];

for (let i=0; i<20; i++){
buttons.push();
}
return buttons;
}


If you wanted to do it in the jsx, something like this should work:



render() {

return (

{[...Array(20).keys()].map()}

);
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...