Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to render a new instance in ReactJS

As an example (real tried code) I have a component of which I want to initiate a NEW instance for rendering.

import React, { Component } from 'react';

export default class TinyObject extends Component {    
    constructor(props) {
        super(props);
        console.log("TinyObject constructor");
    }

    render() {    
        console.log("TinyObject render");
        return (
            <div>HEY THIS IS MY TINY OBJECT</div>
        );
    }
}

Then in main App constructor I do the following:

var myTinyObject = new TinyObject();
var myArray = [];
myArray.push(myTinyObject);
this.state = {testing: myArray};

Then a created a function to render this:

renderTest()
{
    const {testing} = this.state;

    const result = testing.map((test, i) => {
        console.log(test);
        return {test};
    });  
}

And I call this from the App render function like this:

render() {
     const { gametables, tableActive } = this.state;

    console.log("render");
    return <div><div>{this.renderTest()}</div></div>;
}

It runs, no errors. I see console log of the following:

console.log("TinyObject constructor");
console.log(test);

But I don't see console log of the TinyObject render nor do I see the render output.

Thanks to lustoykov answer I got a little further

JSX: var myTinyObject = <TinyObject />;

works!

but in the real app I add a little more and don't know how to do it here.

return <GameTable key={'gt'+index} data={table} settings={this.settingsData} sendTableNetworkMessage={this.sendTableNetworkMessage} />          

this is the way I was rendering; and I needed more instances of GameTable now the question is; how do I add the arguments like data & settings to myTinyObject.

thanks for helping so far.

like image 877
Reneb Avatar asked Oct 18 '22 09:10

Reneb


1 Answers

You don't manually instantiate react component, use JSX or createElement. For instance

via JSX

var myTinyObject = <TinyObject prop1={prop1} prop2={prop2} />;

via React.createElement

var myTinyObject = React.createElement(TinyObject, { prop1, prop2 }, null);
like image 68
Lyubomir Avatar answered Oct 21 '22 09:10

Lyubomir