Kevin
Kevin

Reputation: 443

Escape Character Cannot Working in ReactJS Map Looping

I have file call ArrayCustomer.js contains ARRAY like this:

const ArrayCustomer = [
  {
    index:1,
    kondisi: 'Daftar Baru',
    badge: 'badge btn-warning',
  },
  {
    index:2,
    kondisi: 'Pelanggan dibawah 10m<sup>3</sup>',
    badge: 'badge btn-secondary',
  },
]

export default ArrayCustomer

then I Import that Array to my Component call EditCustomer.js
and in form input I loop use map for showing kondisi like this:

<FormGroup>
  <Label for="status">Status Pelanggan</Label>
  <Input
    required
    value={this.state.status}
    onChange={this.handleChange}
    type="select"
    name="status"
    id="status"
  >
    ArrayCustomer.map(item => (
    <option value={item.index}>{item.kondisi}</option>) ) }
  </Input>
</FormGroup>;

but the Escape Character Does'nt showing as HTML/JSX Tag. I Stack because of this, I hope you can help me. Thanks.

Upvotes: 0

Views: 829

Answers (1)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

You need to use dangerouslySetInnerHTML to render HTML strings in React elements.

decode the HTML string with this function.

const decodeString = str => {
  var element = document.createElement("div");
  element.innerHTML = str;
  return element.childNodes.length === 0
    ? ""
    : String(element.childNodes[0].nodeValue);
};

Update map method, use the decodeString method while adding to element.

ArrayCustomer.map(item => (
  <option
    value={item.index}
    dangerouslySetInnerHTML={{ __html: decodeString(item.kondisi) }}
  ></option>
));

Upvotes: 2

Related Questions