Rikard
Rikard

Reputation: 7805

Passing Node.js data to React

I am refacoring a component to React code.

Previously I was compiling it with Jade and passing the i18n text from a Jade global directly to the HTML. Something like this:

// in Node.js / Express
const text = require('./assets/texts.json');
app.get('/route', (req, res) => {
    render('page', text);
});

and in Jade I would have:

h3= text.en.title
p= text.en.subtitle

Now I am doing this with React and I wonder how to pass data into it?

If I do const text = require('./texts.json'); inside the react file I get a error...

How to pass data from Node to React in the same way as I did with Jade? Is it only possible via Ajax on the client side already?

Upvotes: 1

Views: 3120

Answers (1)

Rikard
Rikard

Reputation: 7805

Ok, so getting downvotes in the question I go for the answer I found...

I ended up passing my text information in my DOM element that will receive my React component. So In Jade I did:

-
    var words = ["calculate_price", "price_info", etc etc... ];
    var text = words.reduce(function(obj, word){
        return (obj[word] = lang[word], obj);
    }, {});
#dialog_wrapper(data-text= JSON.stringify(text))

and in the file where I mount the component:

const dialogWrapper = document.getElementById('dialog_wrapper');
const dialogText = JSON.parse(dialogWrapper.dataset.text);
ReactDOM.render(<BookingDialog text={dialogText}/>, dialogWrapper);

and by last in the React component I did:

componentDidMount() {
    console.log(this.props.text); // all here!
}

Upvotes: 1

Related Questions