Convert string to a jsx string in react | How to convert Unicode escape sequences to Unicode characters in react

1.1k views Asked by At
<Hello name={'\u4ed8\u52a0\u4fa1\u5024\u7a0e# IE9834481A'}></Hello>
class Hello extends Component {
    render() {
        return (
            <div>
                {this.props.name}
            </div>
        );
    }
}

The above 2 code snippets are working fine & giving the result as expected, i.e, the escape sequences are getting converted to the relevant unicode characters.

Now consider, there is an array(dynamically populated) and the array values will be the default value for the input tag & this array contains unicode escape sequences.

Ex: <input value={array[i]}></input>

I have tried doing <input value={<Hello name={array[i]}></Hello>}></input>

But the o/p is [object Object].

If I hardcode the string in input tag, o/p is as expected <input value={<Hello name={'\u4ed8\u52a0\u4fa1\u5024\u7a0e'}></Hello>}></input>

How should I solve this issue, ultimately I want to pre-populate input tag with array value containing unicode escape sequences (after converting to unicode characters).

2

There are 2 answers

0
Drew Reese On

console.log(JSON.parse('"\u4ed8\u52a0\u4fa1\u5024\u7a0e# IE9834481A"'));

2
Flui On

It is not allowed to pass a React Node to the input value. Here is a string expected. If you need the Hi use a function.

const hello = (name) => `Hi ${name}`;


ReactDOM.render(
  <input value={hello('\u4ed8\u52a0\u4fa1\u5024\u7a0e')}></input>,
  document.getElementById('root')
);