How do I pass in a dynamic value using a string literal with tailwind inline css?
For example I want to change the width dynamically, and not use tailwinds premade w-1, w-2, etc...
<div
class="p-1 border-2 width: {createTimeBlock(
show.startTime,
show.endTime,
)}px">
{show.startTime} to {show.endTime}
</div>
The correct syntax would be w-[{...}px], but Tailwind relies to classes to be statically known, so this will probably not work.
The easiest thing would probably be to just use style:width="..." or style="width: ...". Though this will have high precedence due to being an inline style.
Alternatively, you can create a local component class that reads width from a custom property, then set the property using CSS attribute syntax, e.g. --width="..." (for components) or via style as style="--width: ...".
The other way around, if createTimeBlock will return a fixed set of values ( say [v1, v2, .... vN] ) for which there is a fixed set of width values to set ( assuming creatTimeBlock returns only increments of 15mins for example ), you can do this.
<script>
$timeblock = createTimeBlock( startTime, endTime );
</script>
<div
class="p-1 border-2..."
class:width_v1={timeblock === v1}
class:width_v2={timeblock === v2}
...
class:width_vN={timeblock === vN}
>
{startTime} to {endTime}
</div>
<style>
.width_v1{
width: v1_width_px;
}
.width_v2{ width: v2_width_px; }
....
.width_vN{ width: vN_width_px; }
</style>
Note, the actual .width_v1 class can actually be a native width class to tailwind like say w-8.
Hope this helps.
hey I have designed a rectangle using css and it displays a text inside of it , How can I convert this whole component as a means to navigate to some other url (i have tried using the Link from reactrouterDOM but it changed the shape and also an underline appeared just below the text, which defeated the whole point of it not looking like a link text ).
Any Approach Would be helpful as I am quite new to React.Thanks!
If you want to use Link from react-router:
<Link to="/url" style={{
textDecoration: 'none',
color: 'inherit',
display: 'inline-block',
}}>
<Rectangle/>
</Link>
If you just want to handle onClick in rectangle:
export const Rectangle = (props) => (
<div onClick={props.onClick}>whatever</div>
);
and then use it as:
<Rectangle onClick={() => console.log('whatever')}/>
PS: https://reactjs.org/docs/handling-events.html
I'm researching if it is easily possible with React Native or whether I should build a native app.
I want to edit an image from the photo library and add a text overlay to it. Think of it like a postcard with a greeting message on it.
How would I add text to and image and make a new copy of it in react native? I'm not looking for detailed code, just for an explanation on how to get started.
Update:
Would it be a good alternative to just save the coordinates of the message on the picture instead of generating a new image?
You can go with 2 ways. You can either render the text on an image component and save the position of that text or you can process the image and get a new image with the text.
The first option brings up the problem of that position is relative to image's size. Means that if the image renders on a different sized screen the position and size of text should also be moved accordingly. This option needs a good calculation algorithm. Also, another problem could be the rendering times. Text component will render instantly but Image component needs to load the image first. This option also needs a good way of render algorithm.
The second option is not possible without a 3rd party library or some level of native code since react-native doesn't support image processing beyond the limits of CSS. A good and maintained image processing library is gl-react-native-v2. This library helps you to process and manipulate the image as you wish and then save the result with captureFrame(config). This option is more capable of processing file but needs you to save a new image.
Either way is good if the way you go is appropriate for your use case. The decision really depends on your case and preference.
You could use react-native's ImageBackground tag since using the Image tag as a container would give you a yellow box warning.
The sample code for it with overlay is as shown below
<ImageBackground source={SomeImage} style= {SomeStyle} resizeMode='SomeMode'>
{loader}
</ImageBackground>
It would be efficient if you work on the same image by changing the flex property in the styles of the image or you may set the position: absolute to the main image container and assign top , bottom, left, right to the nested container.
Helpful link may be found here
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center', marginTop: 20}}>
<Image
style={{
flex: 1,
width:100,
height:100,
}}
source={require('../imgs/star.png')}
/>
<Text style={{position: 'absolute', fontSize: 20}}>890</Text>
</View>
I'm researching if it is easily possible with React Native or whether I should build a native app.
This sounds very doable in react-native
I want to edit an image from the photo library and add a text overlay to it. Think of it like a postcard with a greeting message on it.
I think I would capture ALL the relevant metadata as an object...
{
image: {
uri: './assets/image.jpg',
height: 576,
width: 1024
},
message: {
fontFace: 'Calibri',
fontSize: 16,
text: 'Happy Holidays!'
boundingBox: {
height: '30%',
width: '30%',
top: 0,
left: 0
}
}
}
With the above detail (and maybe more), you'd then be able to reconstruct the design intent on any device, regardless of size (tablet vs mobile) or pixel depth. The boundingBox would be expressed in terms relative to the image's rendered dimensions. In the above example, the message would be contained in a text box no more than 30% of the image width, 30% of its height, and positioned in the top-left corner.
How would I add text to an image and make a new copy of it in react native?
This eliminates the need to do any screenshotting or actual image manipulation, etc. No need to "make a new copy". Just treat them as two separate and distinct assets, then merge them at render using the metadata you captured.
Final thought: if you "need" to "upload the finished photo to a server" as you stated in another comment to another solution, you can do this serverside using any number of technologies using the metadata as your guide.
You can use position: absolute since adding children to Image is deprecated. Following code will align text in middle (vertically and horizontally) over the image:
<View>
<Image
source={yourImageUrl}
resizeMode={'cover'}
style={{
width: 300,
height: 300
}}
/>
<View style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 300, alignItems: 'center', justifyContent: 'center' }}>
<Text>Your overlay text</Text>
</View>
</View>
If you need to only show a text over the image you can wrap the image in a view and after the image insert a text element with position: 'absolute'. If you want a copy of the image containing the text then you can use the same approach but take a snapshot using react-native-view-shot
As far as I know, the image component can be used as a container so you can do something like this:
<Image>
<Text>{"some text"}</Text>
</Image>
Below code is what I used to add text on image at particular coordinates on image.
Xcode 8.3.2 Swift 3.1
func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica Bold", size: 10)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
] as [String : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
And call above method as below
let imageWithText = textToImage(drawText: "textOnImage", inImage:yourImage, atPoint: CGPoint(x:9,y:11))
There are several libraries available for that. If you want to add a text to an image you can use: react-native-media-editor. This is quite a good option for adding text to an image but I recommend you react-native-image-tools. It provides so much flexibility. You can add a text and position it accordingly. Apart from that, there are filters, cropping option, light adjustments and so much more.
It depends on the use case but if you simply want to put a text on an image, using ImageBackground is a one of the good approach.
Do it like below.
<ImageBackground
source={{ uri: hoge }}
style={{
height: 105,
width: 95,
position: 'relative', // because it's parent
top: 7,
left: 5
}}
>
<Text
style={{
fontWeight: 'bold',
color: 'white',
position: 'absolute', // child
bottom: 0, // position where you want
left: 0
}}
>
hoge
</Text>
</ImageBackground>
I want to change the chat window fontcolor/fontsize of the page younow. I tried 2 'cssText' samples but I'm unable to change the font color to RED. How can I change the chat window font color to RED? I'm using Firefox and greasemonkey.
sample 1:
document.getElementById("chatcomments").style.cssText = 'font-size: 36px; color: red !important;'
sample 2:
document.querySelector(".chatcomments span").style.cssText = 'font-size: 36px; color: red !important;'
click to see the chatimage
you need to be specific with the attributes of the style object:
document.getElementById("chatcomments").style.color = "red";
document.getElementById("chatcomments").style.fontSize = "30px";
If you use JQuery, you can use the css function, like so:
$(".chatcomments > span").css("color", "red");
You do not need to set font-size again if it already has been set. Another issue is that .chatcomments span won't work as they're two different things; instead, > will work: .chatcomments > span.
It is also better to use RGB or hexadecimal values instead of colour names, for example:
$(".chatcomments > span").css("color", "#EE4B38"); //RGB
$(".chatcomments > span").css("color", "rgb(238, 75, 56)"); //Hex
In the case that you're trying to create a custom client-side script in Tampermonkey or Greasemonkey (it looks like you are), you must use // #require to import the JQuery source (as seen in this answer):
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js
el.style.setProperty('color', 'red'); seems more right
I have something like:
const someCSS = `
.foo {
padding: 20px;
background-color: #ddf;
width: 100px;
}
.bar {
height: 100px;
}
.foo {
padding-top: 30px; /* this overrides the previous one */
}
`;
I can add this do the DOM and get back all selectors with each rule like this (jsFiddle):
const style = document.createElement('style');
style.innerHTML = someCSS;
document.head.append(style);
const styleSheet = Array.from(document.styleSheets).find(ss => ss.ownerNode == style);
const rules = Array.from(styleSheet.rules).map(rule => rule.cssText);
function styleToObject(rules, mergeWith = {}) {
return [...rules].reduce(
(obj, rule) => (obj[rule] = rules[rule], obj), mergeWith
);
}
const styleObject = Array.from(styleSheet.rules).reduce(
(obj, rule) => (obj[rule.selectorText] = styleToObject(rule.style, obj[rule.selectorText]), obj), {}
);
document.querySelector('pre').appendChild(
document.createTextNode(JSON.stringify(styleObject, null, '\t'))
);
and get something like this:
{
".foo": {
"padding-top": "30px",
"padding-right": "20px",
"padding-bottom": "20px",
"padding-left": "20px",
"background-color": "rgb(221, 221, 255)",
"width": "100px"
},
".bar": {
"height": "100px"
}
}
Is there another way to have the browser do this, without touching the DOM? I mean have a CSS text parsed by the browser (no regex) without actually styling anything in the page.
I though about adding it to a iFrame, but before its appended to the DOM the document is not available...
The short answer is no, you can't without changing the DOM.
If your concern is the added element triggering a redraw or the loaded style influencing the page in any way, you could add a "never-matching" media rule to the <style>-element you create.
For example:
style.setAttribute('media', '(max-width: 0)');
Working fiddle
EDIT
Was working on an example utilising this trick/hack/solution, you can find it here. Only now noticed the update to the question which is rather similar in mechanics (although my sample will work in less green browsers (not part of the question, I know)).
I've checked some sources which I've come across when I was trying to do a similar thing, most notably MDN - CSSStylesheets is very thorough and states:
A CSSStyleSheet object is created and inserted into the document's
styleSheets list automatically by the browser, when a style sheet is
loaded for a document. As the document.styleSheets list cannot be
modified directly, there's no useful way to create a new CSSStyleSheet
object manually (although Constructable Stylesheet Objects might get
added to the Web APIs at some point). To create a new stylesheet,
insert a or element into the document.
(Emphasis mine. CSO already mentioned by #Ouroborus)
I haven't done a lot of testing on various browsers, but I haven't seen redraws and/or reflows by adding the (media queried) style node to the <head>, unlike adding an <iframe>.
I'm curious if someone out here knows of a solution which relies on the (cross-)browser for processing CSS without hitting the DOM, as I haven't found it and ended up building a Tokenizer/Lexer to create such a tree).