Is it possible to capitalize first letter of text/string in react native? How to do it? - text

I have to capitalize first letter of text that i want to display. I searched for it but i cant found clear thing to do that, also there is no such props for text in react native official documentation.
I am showing my text with following format:
<Text style={styles.title}>{item.item.title}</Text>
or
<Text style={styles.title}>{this.state.title}</Text>
How can I do it?
Suggestions are welcome?

Write a function like this
Capitalize(str){
return str.charAt(0).toUpperCase() + str.slice(1);
}
then call it from <Text> tag By passing text as parameter
<Text>{this.Capitalize(this.state.title)} </Text>

You can also use the text-transform css property in style:
<Text style={{textTransform: 'capitalize'}}>{this.state.title}</Text>

React native now lets you make text uppercase directly with textTransform: 'capitalize'. No function necessary.
import React from 'react'
import { StyleSheet, Text } from 'react-native'
// will render as Hello!
export const Caps = () => <Text style={styles.title}>hello!</Text>
const styles = StyleSheet.create({
title: {
textTransform: 'capitalize'
}
})

Instead of using a function, a cleaner way is to write this as a common component.
import React from 'react';
import { View, Text } from 'react-native';
const CapitalizedText = (props) => {
let text = props.children.slice(0,1).toUpperCase() + props.children.slice(1, props.children.length);
return (
<View>
<Text {...props}>{text}</Text>
</View>
);
};
export default CapitalizedText;
Wherever you're using <Text>, replace it with <CapitalizedText>

just use javascript.
text.slice(0,1).toUpperCase() + text.slice(1, text.length)

TextInput have this to handle using
autoCapitalize enum('none', 'sentences', 'words', 'characters')
for example try like this
<TextInput
placeholder=""
placeholderTextColor='rgba(28,53,63, 1)'
autoCapitalize = 'none'
value ='test'
/>

this worked for me!
labelStyle:{
textTransform: 'capitalize',
fontSize:20,
},

Since this is very general functionality I put it in a file called strings.js under my library:
// lib/strings.js
export const CapitalizeFirstLetter = (str) => {
return str.length ? str.charAt(0).toUpperCase() + str.slice(1) : str
}
And simply import it in the components that need it:
import React from 'react';
import { View, Text } from 'react-native';
import { CapitalizeFirstLetter} from 'lib/strings'
export default function ComponentWithCapitalizedText() {
return <Text>CapitalizeFirstLetter("capitalize this please")</Text>
}

I just added a prototype function, based on #mayuresh answer
String.prototype.Capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
and use it like this:
myStr.Capitalize()

If you want to capitalize only the first letter of the input:
function CapitalizeFirstLetterOfInput () {
const onInputUppercase = (e) => {
let firstLetter = e.target.value.charAt(0);
e.target.value = firstLetter.toUpperCase() + e.target.value.slice(1);
};
return (
<div>
<input onInput={onInputUppercase}/>
</div>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>

if anyone interested doing it by just css/style
<strong style={{textTransform: 'capitalize'}}>{props.alert.type}!
here inner {} is for object {textTransform: 'capitalize'}

This answer worked for me:
text.slice(0,1).toUpperCase() + text.slice(1, text.length)
I used it with a props in an alt tag:
`${(props.image).slice(0,1).toUpperCase() + (props.image).slice(1, (props.image).length)}`
Then I guess you can apply that to any text you want.

Related

tiptap ReactNodeViewRenderer how to render the original view

I'm using tiptap and trying to extend the Paragraph node to wrap some extra stuff around its view. I used <NodeViewWrapper> and <NodeViewContent> as the guides said.
const ParagraphWrapper = () => {
return (
<NodeViewWrapper>
<NodeViewContent />
</NodeViewWrapper>
)
}
const ParagraphExt = Paragraph.extend({
addNodeView() {
return ReactNodeViewRenderer(ParagraphWrapper)
}
})
export default function App() {
const editor = useEditor({
extensions: [
Document,
Text,
ParagraphExt, // <<<< text-align was not rendered
// Paragraph, // <<<< This worked
TextAlign.configure({
types: ["paragraph"]
}),
],
content: `<p style="text-align: center">This is a paragraph</p>`,
})
return (
<>
<EditorContent editor={editor} />
<pre>{JSON.stringify(editor?.getJSON?.(), null, 2)}</pre>
</>
);
}
However, this seems to render the node from scratch. Thus, other extensions, such as textAlign no longer works.
I only need to wrap a thin layer around whatever was rendered originally. How do I do that?
Code Sandbox
You still get access to the attrs being passed to the node which is available in props. You can use that info to style your rendered content as you wish.
const ParagraphWrapper = (props) => {
const textAlign = props.node.attrs.textAlign;
return (
<NodeViewWrapper>
<NodeViewContent style={{textAlign}} />
</NodeViewWrapper>
);
};

Can you use templates in Next.js?

I am fairly new to web development and currently have a rudimentary web server using Node.js, Express, and Pug which I am hoping to convert to Next.js. Is it possible to create re-usable templates (similar to Pug/Jade) in Next.js?
This is how I do mine. There are better ways, but it's how I like it. I came from express handlebars, and have used pug before, so this is how I did mine.
In pages/_app.js file:
import React from 'react'
import Head from 'next/head'
export default function MyApp({ Component, pageProps }) {
const Layout = Component.Layout || LayoutEmpty // if page has no layout, it uses blank layout
const PageTitle = Component.PageTitle // page title of the page
return (
<Layout>
{PageTitle? (<Head><title>{PageTitle}</title></Head>) : '' }
<Component {...pageProps} />
</Layout>
)
}
const LayoutEmpty = ({children}) => <>{children}</> // blank layout if doesnt detect any layout
In your component folder where ever you want to put your layout file: eg component/layout.js
import Link from 'next/link';
import {useRouter} from 'next/router'
export function LayoutOne({children}) {
try {
return (<>
<nav>
<ul>
<li><Link href="/"><a>Home</a></Link></li>
</ul>
</nav>
<div>{children}</div>
</>)
} catch(e) {console.log(e)}
}
Then in your pages: eg pages/about.js
import React, { useState, useEffect } from 'react';
import {LayoutOne} from '../component/layout' // location of your layout.js file
Aboutpage.PageTitle = 'About | Website Tag Line' // set title of your page
Aboutpage.Layout = LayoutOne // using LayoutOne. If you dont do this, its considered blank layout and you'll get no layout
export default function Aboutpage() {
try {
return (
<>
<div>
<h2>About</h2>
</div>
</>
);
} catch(e) {console.log(e)}
}
If you want more layout, in your layout.js file at the end, just change the name of the export function eg: LayoutTwo
export function LayoutTwo({children}) {
try {
return (<>
<nav>
<ul>
<li><Link href="/dashboard"><a>Dashboard</a></Link></li>
</ul>
</nav>
<div>{children}</div>
</>)
} catch(e) {console.log(e)}
}
And one the page, you change layout to two
import {LayoutTwo} from '../component/layout'
Aboutpage.Layout = LayoutTwo

Access theme variables outside withStyles function (react-native-ui-kitten)

I want to use theme variables to style my Icon accordingly. However i cant use style property to fill the Icon element of react-native-ui-kitten but instead have to use the fill property. How can I access theme variables outside of the withStyles function of react-native-ui-kitten
#xk2tm5ah5c
You can use theme property if you wrap your component into withStyles.
Here is an example code:
import React from 'react';
import { View } from 'react-native';
import { Button, Icon, withStyles } from 'react-native-ui-kitten';
const ScreenComponent = (props) => {
const iconColor = props.theme['color-primary-default'];
const FacebookIcon = (style) => (
<Icon {...style} fill={iconColor} name='facebook' />
);
return (
<View>
<Button icon={FacebookIcon}>LOGIN WITH FACEBOOK</Button>
</View>
);
};
export const Screen = withStyles(ScreenComponent);
I'm not quite sure I understand your question completely. Usually when you have a question, you should post some of your code for context.
Here is my answer assuming 'Theme variable' is a hash... Try string interpolation:
fill={`${theme.HEX_COLOR}`}

Maintaining text format when passing around data

I have text(paragraphs) stored in my database that includes line breaks. When I do a GET request to the database, the information comes back as an object. The portion with the text turns into one large clumped up paragraph. Does anyone know how I can maintain the line breaks and text format when passing the text around?
You can split the line breaks into an array and the use the map function to show and style them the way you want. Here's a simple solution that can be further modified according to your needs:
const myObj = {
text: 'Very large text\nLine1\nLine2\nLine3'
};
const text = myObj.text.split('\n');
class App extends React.Component {
render() {
return (
<div>
{text.map((t, i) => <div key={i}>{t}</div>)}
</div>
);
}
}
ReactDOM.render( < App / > ,
document.getElementById('root')
);
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script><div id="root" />

Printing in ReactJS

How do I print(printer) a DIV in my app component in react ? I have a DIV=(badgeContainer) inside which I have added a few shapes, text and Images, now i would like to print the elements inside the DIV=(badgeContainer). Is there a package which would help me do this in react ? Any help is much appreciated.
You can do this using the useRef hook and window.(open & print & close).
import React from "react";
export const Printable = () => {
const printableAreaRef = React.useRef<HTMLDivElement>(null);
const handlePrintClick = () => {
const w = window.open();
if (printableAreaRef.current?.innerHTML) {
w?.document.write(printableAreaRef.current.innerHTML);
w?.print();
}
w?.close();
};
return (
<>
<button onClick={handlePrintClick}>Click To Print</button>
<div ref={printableAreaRef}>
I want to print this
</div>
</>
);
};
There's several libraries you can use for this. I have used https://github.com/MrRio/jsPDF and it's great.
you can you this package :
ReactToPrint - Print React components in the browser
I use it and it can handle print for you

Resources