1linkconst x = <div>Hellow World!</div>
👉 You can use JavaScript variables and expressions inside JSX content:
1linkconst name = 'World';
2linkconst x = <div>Hellow {name}!</div>
1linkconst x = <div>Hellow {name ? name : 'Stranger'}!</div>
If your expression is a callbag, then the element's content will be updated when the callbag has new values.
1linkimport { interval } from 'callbag-common';
2link
3linkrenderer.render(
4link <div>You have been here {interval(1000)} seconds!</div>
5link).on(document.body);
👉 Values of the provided callbag are only listened to while the element lives on the DOM:
1linkconst name = state('Jack');2linkconst div = <div>Hellow {name}!</div>;3link4linkconsole.log(div.textContent); // > Hellow !5link6linkrenderer.render(div).on(document.body); // --> now `div` starts listening to `name`7linkconsole.log(div.textContent); // > Hellow Jack!8link9linkname.set('John'); // --> `div` updates itself with `name`10linkconsole.log(div.textContent); // > Hellow John!11link12linkrenderer.remove(div); // --> `div` stops listening to `name`13linkname.set('Jonas'); // --> so this update will be missed14linkconsole.log(div.textContent); // > Hellow John!
JSX content is escaped by default, so HTML strings would be rendered as if they were strings.
However sometimes it is useful to set content of an element directly to some HTML string,
similar to setting element.innerHTML
.
To do this, simply set the _content
attribute of your element:
1linkimport marked from 'marked';
2link
3linkconst input = state('');
4linkconst markdown = expr($ => marked($(input)));
5link
6linkrenderer.render(<>
7link <textarea _state={input} placeholder='type some markdown ...'/>
8link <div _content={markdown}/>
9link</>).on(document.body);
⚠️ WARNING ⚠️
Using
_content
attribute might allow attackers to inject their own JavaScript into your webpage, which allows them access to data that otherwise would only be available to your own JavaScript (data such as cookies). This type of attack is known as XSS attack and the best way to protect against it is to check custom HTML generated from user input before adding it to the DOM.