1

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?

5
  • you could use json-loader github.com/webpack/json-loader, but maybe your question is more about express? Commented Aug 11, 2016 at 19:15
  • @Daniel_L in that case the whole json file with all languages would be loaded via JavaScript to the client right? I would like to just add the correct translated words server side to reduce data loaded by client. Commented Aug 11, 2016 at 19:18
  • I supose I could add a data-text attribute with a json string in the element where react is going to mount... but wonder if there is another more clean way. Commented Aug 11, 2016 at 19:20
  • you can have another script that exports only what you need from your json file Commented Aug 11, 2016 at 19:20
  • ya it sounds like this is something you would fetch from your server as your root component mounts Commented Aug 11, 2016 at 19:21

1 Answer 1

1

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!
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.