I would like to display emojis on my webpage in a react chat app. The plan is to give the user a list of emojis to select from. How do I use the codes like '1F683' and have them display the emoji on the page? I need to support Chrome.
I am able to use css to show the emoji.
<div className="smiley"></div>
.smiley:after {
content: "\01F683";
}
I can also have a list of images and map them to the code and display an img element per emoji.
Is there another way and which is the best way to do this?
I am maybe late to the party but I needed to conditionally render different emojis by the same component, so for me the easiest way was:
Go to https://unicode.org/emoji/charts/full-emoji-list.html
Find needed emojis, for example U+1F609 and use it as a string of a hex number 0x1F609 with String.fromCodePoint in your code — see below.
Create one little component to satisfy eslint rule which would otherwise throw an error
Emojis should be wrapped in <span>, have role="img", and have an accessible description with aria-label or aria-labelledby jsx-a11y/accessible-emoji:
const Emoji = React.memo(({ className, label, symbol }) =>
<span className={className} role="img" aria-label={label}>
{String.fromCodePoint(symbol)}
</span>)
export default Emoji
So then somewhere else you can use it as:
class MagnificentComponent extends PureComponent {
getEmojiConditionally = () => this.props.happy ? '0x1F60A' : '0x1F61E'
render = () =>
<SomeComponentWhereINeedEmoji>
<Emoji symbol={this.getEmojiConditionally(} />
</SomeComponentWhereINeedEmoji>
}
All emojis are pretty much standardized with the format at Emoji Cheat Sheet, so your given example above (\01F683) maps to railway_car in the Emoji Cheat Sheet.
It might be a better idea to store your emojis with these identifiers and map it to the actual emojis later on, without worrying about encoding the actual emoji (🚃) themselves, or not being able to tell/remember the actual emoji represented by the Unicode sequence (\01F683).
If you wish to map this human-readable identifier to the actual Unicode sequence/symbol itself, you have a few options, using railway_car as an example:
Twemoji Awesome
Twemoji Awesome is like Font Awesome, but with Twitter Emojis.
You can then insert an emoji like this, just like Font Awesome.
<i class="twa twa-railway-car"></i>
This will output the corresponding SVG:
Emoji Dictionary
There's an npm package aptly named emoji-dictionary that allows you to map the emoji name to the Unicode character, if you wish to use default the browser's default emoji renderer.
The usage will then look like this:
emoji.getUnicode("railway_car");
This returns 🚃 (which would display on modern browsers/might break on older browsers/etc).
We have the unicode of emojis in W3C .
It is in the range of {. Hex 2600-26FF.}.
Thus, you can generate it without CSS.
Check example below 👇🏼
class Emoji extends React.Component {
render() {
const {title, code} = this.props;
return <span className="emoji" title={title}>{code}</span>
}
}
class App extends React.Component {
renderEmojis() {
const rangeEmojis = Array.from({length: 256}, (v, k) => (k + 9728).toString(16));
return rangeEmojis.map((code, index) => <Emoji code={unescape ('%u' + code)} title={"My code is :"+code} key={'emj'+index} />)
}
render() {
return (
<div>
{this.renderEmojis()}
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector('#chat'))
.emoji {
border: solid 1px #3e3e3e;
width: 50px;
height: 50px;
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<section id="chat" />
They are many ways to use emoji's in react. With NPM and also without it by a "span" tag.
<span role="img" aria-label="arrow">➡️</span>
I find this simple and easy to use.
React code for Grinning face with big eyes:
<div>
{String.fromCodePoint('0x1f603')}
</div>
Output:
😃
Full Emoji List, v15.0 - https://unicode.org/emoji/charts/full-emoji-list.html
--
Putting this here just incase anyone else stumbles on this post looking for what I needed.
<p>
After a lot of Googling and reading I just copy/pasted the emoji, it seems to work fine 🤷♂️.
</p>
To get the emoji I went to Discord sent the emoji I needed and copy/pasted it into my code and it shows up on screen.
Related
Apologies if this shows how much of a novice I am, but I'd like to know more about dynamic variables and CSS in Vue. I'd like to create a system where each time a button is pressed, the letters of the button label become further apart.
Inside a component is it possible to use a counter script such as:
<script>
export default {
name: 'Counter',
data() {
return {
count: 3,
}
},
methods: {
intrement() {
this.count += 1;
}
}
}
</script>
And then use the count integer value to change CSS text spacing for example?
So that in the template, I could use:
<template>
<header>
<div>
<button class="header_button" style="letter-spacing: `v-bind(count) + ch`;">MYBUTTON</button>
</div>
</header>
</template>
I appreciate this is a strange and specific example, but if anyone could give me some feedback as to why this doesn't work, as well as suggestions on how I could achieve this I'd be super appreciative.
In that case, you can directly use the following
<button :style="`letter-spacing: ${count}ch;`">
Here is a playground.
PS: :style is a shorthand for v-bind:style as explained here.
v-bind for CSS (mixing script + style) is also a thing.
Here, you're only using script + template combo, so an interpolation is enough.
I'm trying to hide the eye(Password Reveal control) which appear while entering password in inputbox in Microsoft Edge. For hiding it, we need to use :-ms-reveal. I tried to use it like MsReveal in inline style of react, but didn't work. Due to CSS file restrictions, I need to use inline styles in my project. So could anyone help me in resolving this issue?
It took almost a day to find the solution which I was looking for. Scenario was if you don't want to use 3rd party packages like Radium or Emotion (css-to-js), you can follow below method.
Use Template Literals for adding your code.
const inputFieldStyle = `
.inputField::-ms-reveal{
display: 'none'
}`
Then you can use <style> tag where you pass above style like below:
const reactFunctionalComponent = (props) => {
...
return(
<>
<style>
{inputFieldStyle}
</style>
...
</>
)
}
Let's say I have a variable named data in app.component.ts which is of type :string.
In app.component.html I am showing the value of data to the UI using string interpolation like {{data}}.
Now my question is while displaying the value in a UI, I need to apply some css to some specific letters present in a data variable.
For example:
app.component.ts
data : string = "stack overflow"
app.component.html
<p>{{data}}</p>
How to highlight the background color of the word overflow using css?. And I hear that Pipes can be used to modify the value. But here I am in a need of applying css.
And one more constraint is there, initially the value will be displayed to the browser; the word to be highlighted will be coming from input box.
You could use something among the lines of:
.ts
highlightKeyWord(sentence: string, keyWord: string) {
sentence = sentence.replace(keyWord,
`<span style="background-color: #35a5f8;">${keyWord}</span>`);
return this.sanitizer.bypassSecurityTrustHtml(sentence);
}
.html
<p [innerHTML]="highlightKeyWord('hello world', 'world')"></p>
One solution is use pipe to extract given word into separate <span> elements:
#Pipe({
name: 'letterByLetter'
})
export class LetterByLetter implements PipeTransform {
transform(value: string): string {
return value
.split('')
.map((letter) => {
return `<span>${letter}</span>`;
})
.join('');
}
}
Then in component there is possibility to use the pipe in this way <div [innerHTML]="data | letterByLetter"></div>. Notice i've used innerHtml but you can use DomSanitizer instead - which should be better)
After that you are able to decide how the span element should looks. You can set either the class or style directly.
Good luck!
I have a <span> that I want to apply dynamic style to.
Style is stored in a css-like string variable and can be arbitrary e.g.
myStyle = 'color: white; font-weight: bold;'
or
myStyle = 'background-color: red;'
I expected it to work like
<span style="{{myStyle}}">
but it didn't.
I tried different options but none seem to work for me for different reasons:
I can't put styles in a .css file and use class names because style is coming from server in the form of aforementioned string
Using [style.color] etc. doesn't suit me because I don't know what the style can be
Using [ngStyle] doesn't suit me because it expects object like {'color': 'red', 'font-weight': 'bold'} and I only have string
The reason I have a style stored in a string is because I need to apply it in HTML generated on the server where I simply pass that string to a placeholder variable in a velocity template.
I am almost confident that it can't be done the way I want but probably I am overlooking some solution.
All you need is DomSanitizer and bypassSecurityTrustStyle
Component side :
import { DomSanitizer } from '#angular/platform-browser';
constructor(private doms : DomSanitizer) {}
newStyle = 'background-color:red';
safeCss(style) {
return this.doms.bypassSecurityTrustStyle(style);
}
Template side :
<p [style]="safeCss(this.newStyle)">
Start editing to see some magic happen :)
</p>
WORKING DEMO
Angular provides the DomSanitizer service which can convert strings into style objects. I think this is exactly your case.
constructor(private sanitizer: DomSanitizer) {
}
sanitizeStyle() {
return this.sanitizer.bypassSecurityTrustStyle('background-color: red');
}
<span [style]="sanitizeStyle()">
I think I will go the way of converting the incoming css string into a style object and then applying it to <span> using [ngStyle]
I'd like to attach images to specific words but cannot find the right CSS selector to do so.
I have a portion of my site which displays data as it's pulled from a database, so adding classes or id's to certain words is not an option for me. I need the css to simply display a background image wherever that word (or in this case, name) is found on the page.
For example, in the following (which is pulled from a database):
<td class="data1"><font face="Verdana, Arial, Helvetica, sans-serif" size="1">Patrick</font></td>
I would like to add a background image where the name Patrick is found.
I tried variations of,
td[.table1 *='Parick'] {
background-image:url(../images/accept.png);
but that didn't get me anywhere. And since it's not in a <span> or <div> or even a link, I can't figure it out. If you have any ideas or a jQuery workaround, please let me know. Thanks!
If you can guarantee the names only appear as the only text nodes in elements, you can use a simple jQuery selector...
$(':contains("Patrick")').addClass('name');
jsFiddle.
If there may be surrounding whitespace and/or the search should be case insensitive, try...
$('*').filter(function() {
return $.trim($(this).text()).toLowerCase() == 'patrick';
}).addClass('name');
jsFiddle.
If you need to find the name anywhere in any text node and then you need to wrap it with an element, try...
$('*').contents().filter(function() {
return this.nodeType == 3;
}).each(function() {
var node = this;
this.data.replace(/\bPatrick\b/i, function(all, offset) {
var chunk = node.splitText(offset);
chunk.data = chunk.data.substr(all.length);
var span = $('<span />', {
'class': 'name',
text: all
});
$(node).after(span);
});
});
jsFiddle.
I would recommend using the third example.