My FeedDiscussionsHeadless CMS
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Combine two things

DK's photo
DK
·Dec 20, 2017

Playing around with ReactJS.

I have a conditional that checks if stepMsg is an array or not and then creates either a list (when type = li) or a div, or just uses stepMsg when it isn't an array.

The other code is a for loop that replaces {input...} inside of stepMsg with other words. It's only working if stepMsg isn't an array.

Now my question: How can I combine these two codes?

// stepMsg could be 'Hello {input1}' or ['Hello', '{input2}']
// savedInputs is an array with dynamic content [{id: 1, value: 'yo'}{}...]

if (stepMsg.constructor === Array) {
  if (this.props.type === 'li') {
    stepMsg = stepMsg.map((index, key) => (
      <UL key={key}><Li><InsideLi>{index}</InsideLi></Li></UL>
    ));
  } else {
    stepMsg = stepMsg.map((index, key) => (
      <div key={key}>{index}</div>
    ));
  }
}

// only works without ARRAY
for (var element of savedInputs) {
  stepMsg = stepMsg.replace(new RegExp('{input' + element.id + '}', 'g'), element.value);
}

this.state = {
  message: <div>{stepMsg}</div>
};