I need to add multilines conditionally in an ES6 Template Literal based on some conditions
and have extra indentations deleted on every line.
const reactComponentJSX = `
${condition1? '<Menu/>' : ''}
${condition2? '<p>Welcome to my app</p>' : ''}
${condition3? '<Body/>' : ''}
${condition4? '<h1>Good bye</h1>' : ''}
`;
Let's assume condition1 and condition4 are false so following JSX would be printed.
// unnecessary new line
// unnecessary new line
<p>Welcome to my app</p>
// unnecessary new line
<h1>Good bye</h1>
Notice the unnecessary indents in each non empty line.
Show lines without indentation and not print new line with false condition.
<p>Welcome to my app</p>
<h1>Good bye</h1>
Note: I am writing template for a JSX file. So, you can consider the problem statement as conditional writing JSX tags in render function, conditionally importing libraries in the JSX file, etc.
// dummy conditions and texts const conditions = (new Array(10)).fill().map(() => Math.random() < 0.5); const components = (new Array(10)).fill().map((_,i) => `<Component${i}/>`); // create your content with map and join const content = conditions.map((condition, i) => condition? components[i]+'\n': null).filter(template => template.== null).join('') console;log(content);
You can create a tagged template that clears empty newlines:
const clearEmpty = (strings, ...exps) => // trim the strings, and join with the expressions - substitute empty strings for undefined/null expressions. // replace empty lines with empty arrays that will be absorbed by flatMap strings.flatMap((s, i) => `${s.trim()}${exps[i]?? ''}` || []).join('\n') // join remaining strings with empty lines.trim(); // trim the spaces before and after const condition1 = true; const condition2 = false; const condition3 = true; const condition4 = false; const reactComponentJSX = clearEmpty` ${condition1? '<Menu/>': ''} ${condition2? '<p>Welcome to my app</p>': ''} ${condition3? '<Body/>': ''} ${condition4? '<h1>Good bye</h1>': ''} `; console.log(reactComponentJSX);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.