React NextJs Add Link as componenet into a string - next.js

I need to build nextJs links programatically.
A simple example:
const link = <Link href={'/example'}>ipsum</Link>
const text = 'Lorem ipsum dolor sit amet'
const replaced = text.replaceAll('ipsum', link);
But the result is:
Lorem [object Object] dolor sit amet
How can i replace a string with a link componenet without destroying the react component?
Thank you

Concatenating components in a string will result in displaying [object Object] because eventually that component is an object and will get coerced into a string to fit in.
What would work in react to achieve your goal is to use arrays instead.
const link = <Link href={'/example'}>ipsum</Link>
const text = 'Lorem ipsum dolor sit amet'
const res = text.split(" ").reduce((acc, curr) => {
if (curr === "ipsum") {
return [...acc, link];
}
return [...acc, ` ${curr} `];
}, []);
return <>{res}</>
The fragment would display the array of objects as you expect it to be.

Related

How do I import a Google Font with a space in the title in Next.js with #next/font/google?

The Next.js documentation on importing Google Fonts shows this recommended method of importing Google fonts:
import { Inter } from '#next/font/google'
const inter = Inter({ subsets: ['latin'] })
export default function MyComponent() {
return (
<main className={inter.className}>
Lorem ipsum dolar set amut
</main>
)
}
This method works for the Inter font and other fonts with single word titles. I'm trying to import a font called Redacted Script which has a space in the title.
I tried just TitleCasing it:
import { RedactedScript } from '#next/font/google'
const redactedScript = RedactedScript({ subsets: ['latin'] })
export default function MyComponent() {
return (
<main className={redactedScript.className}>
Lorem ipsum dolar set amut
</main>
)
}
However this code gives me the error:
`#next/font` error:
Unknown font `RedactedScript`
How do I use #next/font/google to import a Google font with a space in it like Redacted Script?
Thanks to a really cool guy at Vercel helping me debug this I've got the answer: Capital_Snake_Case!
Here's the working code:
import { Redacted_Script } from '#next/font/google'
const redactedScript = Redacted_Script({ subsets: ['latin'] })
export default function MyComponent() {
return (
<main className={redactedScript.className}>
Lorem ipsum dolar set amut
</main>
)
}

Display Multiple Variants in Storybook Without Multiple Stories?

I am building a Storybook and would like to display multiple variants of the same component in the 'Docs' tab, without creating new stories under the component in the left nav. Is this possible?
For example, I have the following component:
export const Template = (args) => (
<Alert {...args}></Alert>
)
<Canvas>
<Story
name="Filled Alert"
args={{
children: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
severity: 'info',
variant: 'filled'
}}>
{Template.bind({})}
</Story>
</Canvas>
This component has multiple severity values that I would like to show ('info', 'success', 'warning', 'error'). If I create another <Story> to show that variant in the documentation:
<Story
name="Filled Alert - Success"
args={{
children: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
severity: 'success',
variant: 'filled'
}}>
{Template.bind({})}
</Story>
In this case, I'll get two entries under 'Alert' for each of the stories above. What I'd like though is only a single 'Filled Alert' entry. The Canvas showing a single component that can be played with and the Docs showing my MDX documentation.
But (to make it more tricky), I am trying to get a unique entry for each variant property. So:
Alert
Filled Alert
Standard Alert
Outline Alert
Each of the sub-bullets showing different severity, but not creating new children.
Have you tried using #addon-knobs as referenced on this SO post?
The #addon-knobs has been deprecated in favor of #addon-controls.

How do I select my CSS module class using document.querySelector?

I want to be able to select styles.scrollValue using the document.querySelector()
import { useEffect } from "react";
import styles from "./Navbar.module.scss";
const Navbar = () => {
const handleScroll = () => {
document.querySelector(styles.scrollValue).innerHTML = scrollY;
};
useEffect(() => {
document.addEventListener("scroll", handleScroll);
return () => {
document.removeEventListener("scroll", handleScroll);
};
});
return (
<nav className={styles.navbar}>
<div className={styles.content}>
<h1 className={styles.scrollValue}>0</h1>
</div>
</nav>
);
};
Running this code I get an error:
TypeError: document.querySelector(...) is null
I know I can add a global class to that element doing this:
className={`${styles.scrollValue} scrollValue`}
But that would ruin the advantage of using CSS Modules.
Is there a way to select the CSS Module class without adding another one to it?
You need to select it as a class,
document.querySelector(`.${styles.scrollValue}`)
Calling styles.property returns a value such as the following,
scrollValue: '_src_styles_module__scrollValue'
So when you call document.querySelector it's looking for _src_styles_module__scrollValue which has no selector type such ., or # which makes it look for an element that would match <_src_styles_module__scrollValue> (in this case). Since there is no element with that name or the hashed name it will return null.
Working demo

How can hide storybook control per story arg

I have rails engine project using storybook and mdx files to specify the controls
but i need to hide specific control per story
<Meta
title='Label Component'
story='with_tooltip'
args={{
object: 'employee',
field_name: 'name',
text: 'Employee name',
tooltip: 'Lorem ipsum dolor sit amet, consectetur adipiscing eli'
}}
/>
I have two stories [label,with_tooltip]
in case label story i need to hide tooltip control
I'm using view component preview to show components
You can disable controls for individual properties of a story including the prop table documentation, or you can disable only the control and leave the prop table documentation intact.
To disable the control and prop table documentation for the tooltip prop:
<Meta
title='Label Component'
story='with_tooltip'
args={{
object: 'employee',
field_name: 'name',
text: 'Employee name',
tooltip: 'Lorem ipsum dolor sit amet, consectetur adipiscing eli'
}}
argTypes={{
tooltip: {
table: {
disable: true
}
}
}}
/>
To disable the control but leave the prop table documentation intact for the tooltip prop:
<Meta
title='Label Component'
story='with_tooltip'
args={{
object: 'employee',
field_name: 'name',
text: 'Employee name',
tooltip: 'Lorem ipsum dolor sit amet, consectetur adipiscing eli'
}}
argTypes={{
tooltip: {
control: false
}
}}
/>
See the Storybook docs on disabling controls for specific properties.
The best approach is doing this:
export default {
title: 'Pages/Login ',
component: Login,
parameters:{
controls:{
exclude:/.*/g
}
}
} as ComponentMeta<typeof Login>;
For someone searching for a way to remove the control and change the control count, use amir's answer:
parameters:{
controls:{
exclude:/.*/g
}
}
But changing the regex '/.*/g'(used to remove all the controls) for either:
Another regex that works for you.
A string with the name of the control you want to disable.
The following regex, changing the passing the names of the controls you want to disable between pipes(|).
(?:\b|')(string1|string2|string3)(?:\b|')
For anyone that wants the explanation for the regex, you can read this comment.

Is it possible to use css in .js file in a react app?

I want to map .js file. I need to apply some CSS too. Is it possible to place CSS in a .js file?
I have a constant file at src > Constant > AboutMyselftProgressCount.js and it's code is as below:
const AboutMyselfProgressCount = [
{
ProgressCountTitle: "USER REACHERS",
},
{
ProgressCountTitle: "WEB DESIGN",
},
{
ProgressCountTitle: "UI DESIGN",
},
{
ProgressCountTitle: "ILLUSTRATION",
},
]
export default AboutMyselfProgressCount;
Now I've another .js file at src > Routes > Home > Components > AboutMyself > Components > SkillsContent
The code is as below:
import React from 'react'
import { Row, Col } from 'react-bootstrap'
const Skills = (props) => {
return (
<>
{props.ProgressCountTitle}
</>
)
}
export default Skills;
Basically in this section I've some stuff that I'm using with props
Now, I've one another .js file at src > Routes > Home > Components > AboutMyself > index.js in which I'm mapping data from No. 1 and No. 2
The code is as:
import React from 'react'
import './style.scss';
import Skills from '../AboutMyself/Components/SkillsContent/index'
import AboutMyselfProgressCount from '../../../../Constant/AboutMyselfProgressCount'
const AboutMyself = () => {
return (
<>
<div className='AboutMyselfBackground'>
<div className='AboutMyselfContent'>
<div className='content'>
<p>ABOUT MYSELF</p>
<h4>
I’m a Creative director based on New York, who loves clean, simple & unique design. I also enjoy crafting..
</h4>
<a href=''>DOWNLOAD RESUME</a>
<div className='borderTop'></div>
{
AboutMyselfProgressCount.map((val, ind) => {
return (
<Skills
key={ind}
ProgressCountTitle={val.ProgressCountTitle}
/>
)
})
}
<div className='skillsPara'>
<p>
Proin laoreet elementum ligula, ac tincidunt lorem accumsan nec. Fusce eget urna ante. Donec massa velit, varius a accumsan ac, tempor iaculis massa. Sed placerat justo sed libero varius vulputate.
</p>
</div>
</div>
</div>
</div>
</>
);
}
export default AboutMyself;
All I want to show a progress bar of skills under ProgressCountTitle which is being done using css. So is this possible to place that css of progress bar(s) in file No. 1 using array of objects, array of object(s) as a key value of an object, etc. etc.
I hope I'm clear to all of you with my question.
A CSS component for React is Styled-Component. You can specifically design out your element within the same JS file and assign them by unique element name. https://styled-components.com/
This example was taken direct from their documentation
// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// Create a Wrapper component that'll render a <section> tag with some styles
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
// Use Title and Wrapper like any other React component – except they're styled!
render(
<Wrapper>
<Title>
Hello World!
</Title>
</Wrapper>
);
Yes ofcourse you can
just create any .css file and import in react component.
import './App.css'
and then you can simply add your classNames to your JSX as follows.
<div className='myclass'>
hello world
</div>
if you want mode advance feature like preventing the global styles and using component bases local styles you can also use css modules in reactjs.
you need to name the css file as anyfilename.module.css
then you need to import like:
import classes from './anyfilename.module.css'
then you can add your style classes to jsx as follows:
<div className='myclass'>
hello world
</div>
to learn more click here

Resources