1

I have a code that returns a string, but since it's on render it needs to be accompanied by an HTML tag, in this case span.

I want to use this code in multiple places including placeholders and labels, but with span, I believe that's impossible.

Here's the code in question, would appreciate some ideas on how to fix.

let LocalizedString = React.createClass({
 render: function() {

    if (!this.getKey(loadLang, this.props.xlKey)) {
        return <span>{this.props.xlKey + ' untranslated in ' + userLang + ' JSON'}</span>;
    } else {
        return <span>{this.getKey(loadLang, this.props.xlKey)}</span>;
    }
},

getKey: function(obj, str) {
    str = str.replace(/\[(\w+)\]/g, '.$1'); // let's convert indexes to properties
    str = str.replace(/^\./, ''); // gets rid of leading dot

    let a = str.split('.');

    for (let i = 0, n = a.length; i < n; i++) {
        let key = a[i];

        if (key in obj) {
            obj = obj[key];
        } else {
            return null;
        }
    }
    return obj;
},
});

module.exports = LocalizedString;

In another file that calls LocalizedString, I have this, but makes placeholder return undefined...

<TextField alert={alerts.username} onChange={this._onChangeUsername} placeholder={<LocalizedString xlKey='pages.signin.general.username'/>} ref="username" value={this.props.username}/>

Bottom line is pretty much, can I make render return just a string without any tags or make placeholder accept and discard the span tag?

Regards.

2
  • 2
    AFAIK no. But why does LocalizedString have to be a React component at all? Commented Nov 2, 2015 at 17:01
  • Work crew asked me to redo my original code, which was just a function call into a component for better accessibility... because typing in getKey('keyname') was too much, I guess... Commented Nov 2, 2015 at 17:03

1 Answer 1

1

You must have to use a function instead of a React Component as per the requirement.

React Component's render method must be bound to return single wrapped markup or essentially a Virtual DOM.

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.