Sign in
Log inSign up

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>
};
Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct