Ajay Kumar
Ajay Kumar

Reputation: 151

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

Upvotes: 1

Views: 68

Answers (1)

biphobe
biphobe

Reputation: 4818

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>
        )
    }
})

Upvotes: 2

Related Questions