Search code examples
javascriptjsonobjectreactjsreactjs-flux

React: show object as working JS format?


I am working on a project in which I get into given situation:

myjson:
{
    completeName: "my name is {this.state.myName+ " "+this.state.surname}"
}

component.js

var Component = React.createClass({ 
    getInitialState: function() {
        return({
            myName: "AKHA",
            surname: "HUND"
        })
    },
    render: function() {
        return (
            <div>{myData.completeName}</div>
        )
    }
})

but I am getting output as:

my name is {this.state.myName+ " "+this.state.surname}

instead of:

my name is AKHA HUND***

please help me.

Note: using ES5.

Thanks


Solution

  • What you store in your .json is a string, not an expression, it is not evaluated in any way, you have to modify the template in your JS code.

    Using ES5 you could do something like this:

    .json

    {
      completeName: "my name is %myName %surname"
    }
    

    component.js

    var Component= React.createClass({
        getInitialState: function(){
            return({
                myName: "AKHA",
                surname: "HUND"
            })
        },
        render: function(){
            const result = myData.completeName
                .replace("%myName", this.state.myName)
                .replace("%surname", this.state.surname);
    
            return (
                <div>{ result }</div>
            )
        }
    })