Best way to change vue slots pattern into React? - javascript

In my vue application, i am using slots for some block of contents. Now, i have to migrate my application into react. While exploring react, i got to know props.children will work similar as slot works.
But, i am not sure what will be the proper way to use this pattern in react.
Here is the sample of code in vue
<template>
<div class="badge-box">
<span :class="badgeClass" :style="badgeStyle">
<span v-if="shape !=='dot'" class="line-break">
<slot>
{{text}}
</slot>
</span>
</span>
<span v-if="shape ==='dot'" class="line-break" style="margin-left: 8px;">
<slot name="dotShape">
{{text}}
</slot>
</span>
</div>
</template>
<script>
export default {
name:'sample'
props: {
text: { type: string }
}
}
</script>
How to change this vue slot pattern into React using props.children?

There are several patterns in React that correlate closely with Vue slots.
props.children can be used, but only for default slot with no slotProps. For named slot additional props can be used. Default slot content <slot>{{text}}</slot> can be conditionally rendered when no children are provided:
let MyComp = props => (
...
<div class="default-slot">{{props.children ?? props.text}}</div>
...
<div class="named-slot">{{props.named ?? props.text}}</div>
...
)
and
<MyComp named={<p>Named content</p>}>
<p>Default content</p>
</MyComp>
Function as child and function as prop patterns serve the same purpose but allow to replace slots with slotProps. A child can pass parameters to parent scope through a callback:
let MyComp = props => (
...
<div class="default-slot">{{props.children?.('foo') ?? props.text}}</div>
...
<div class="named-slot">{{props.named?.('bar') ?? props.text}}</div>
...
)
and
<MyComp named={param => <p>Named content {{param}}</p>}>{
param => <p>Default content {{param}}</p>
}</MyComp>

Assuming you are using JSX/TSX in functional React
const Component ({text}) => {
return (
<div class="badge-box">
<span :class="badgeClass" :style="badgeStyle">
<span v-if="shape !=='dot'" class="line-break">
{{text}}
</span>
</span>
<span v-if="shape ==='dot'" class="line-break" style="margin-left: 8px;">
{{text}}
</span>
</div>
)
}
will do what you want. If you are using class component, put it in the render method.

Related

How to call a component inside a custom component in React?

I want to change the body dynamically, how can i do this?
import React from 'react'
// import { Link } from 'react-router-dom'
export default function ProjectTemplate(props) {
const Css= {
"--background":`${props.isValue ? props.mode : 'red'}`
}
return (
<>
<div className="bodyCon projectCon">
<div className="bodyComponent">
<div className="aboutHeading projectHeading" style={Css}>
<h1>{props.name}</h1>
<div className="container">
<div className="projects">
</div>
</div>
</div>
</div>
</div>
</>
)
}
this is a custom component
import React from 'react'
import ProjectTemplate from '../Projects/ProjectTemplate/ProjectTemplate'
export default function Blog(props) {
return (
<>
<ProjectTemplate name='Blog' mode={props.mode} isValue={props.isValue} >
hhhh
</ProjectTemplate>
</>
)
}
this is the another component where i want to add the body of previous component dynamically, then the hhh is not display in browser
output in browser:
<div className="bodyCon projectCon">
<div className="bodyComponent">
<div className="aboutHeading projectHeading" style={Css}>
<h1>{props.name}</h1>
<div className="container">
<div className="projects">
hhh
</div>
</div>
</div>
</div>
</div>
but hhh is not visible in browser, how can i do for this output
You should read this docs, all you need here is children props
The word hhh will not be displayed because you are calling the custom component in the project template with no props name which you want to display. In your code if you render the component the Blog name will displayed only.
use this in the project template and pass the props to the childrenanme
<div className="projects">
{props.childrenanme}
</div>
To Answer your Question: Yes we can use component inside nested component in react.
In JSX expressions that contain both an opening tag and a closing tag,
the content between those tags is passed as a special prop React Documentation.
And to use these special props you have to use {props.children}.
In your example, you have passed the content b/w opening and closing tag of a custom component but forgot to use it.
In projectTemplate component use the children that you have passed while invoking the component, like this:
<div className="projects">
{props.childrenanme}
</div>

Vue accessing a child components computed property

So I'm using a third party vue component called 'vue-tree-list' here's the link -> https://github.com/ParadeTo/vue-tree-list
in the component it has a computed property that basically analyzes the tree structure to find the right place for a new leaf/node to be inserted.
In my parent component I did this:
<template>
<div class="py-8 px-5" style="min-height: calc(100vh - (112px + 2.75rem))">
<div class="flex flex-col w-full">
<button class="cursor-pointer relative flex flex-row items-center h-10 focus:outline-none "
>
<span class="text-sm tracking-wide truncate ml-6">Add Node</span>
</button>
</div>
<VueTreeList
#click="onClick"
#change-name="onChangeName"
#delete-node="onDel"
#add-node="onClick"
ref="tree"
:model="data"
default-tree-node-name="New Depot"
default-leaf-node-name="New Driver"
v-bind:default-expanded="false"
>
<template v-slot:leafNameDisplay="slotProps">
<a class="text-orange-primary mr-4">
<span>{{ slotProps.model.name }}</span>
</a>
</template>
<span class="icon" slot="addTreeNodeIcon">📂</span>
<span class="icon" #click.stop="test()" slot="addLeafNodeIcon">+</span>
^INSTEAD OF CALLING THE DEFAULT EVENT 'add-child' WHICH IMMEDIATELY INSERTS A NODE I DIVERTED IT INSTEAD SINCE I WANT THE USER TO INPUT THEIR DATA BEFORE INSERTING INSIDE THE TREE
<span class="icon" slot="editNodeIcon">📃</span>
<span class="icon" slot="delNodeIcon">✂️</span>
<span class="icon" slot="leafNodeIcon">🍃</span>
<span class="icon" slot="treeNodeIcon">📂</span>
</VueTreeList>
<Modal ref="modal" :title="modalTitle" :size="modalSize" :height="modalHeight">
<div v-if="modalContent == 'new'">
<DriverLookUp />
<VehicleLookUp />
</div>
</Modal>
</div>
</template>
<script>
import { VueTreeList, Tree, TreeNode } from 'vue-tree-list'
import { DriverLookUp, VehicleLookUp } from '#/components/forms/depot'
export default { ONLY ADDED THE RELEVANT FUNCTIONS SINCE IT WOULD BE VERY LONG
components: {
VueTreeList, Modal, DriverLookUp, VehicleLookUp
},
test(){
this.$refs.tree.rootNode() <--- the computed method that I want to access
},
}...
The problem with this is that the computed property for some reason throws an error on missing properties which doesn't make sense since it has already been rendered. Is there a way to trigger a child components computed property?
https://github.com/ParadeTo/vue-tree-list/blob/master/src/VueTreeList.vue <--- here's the link of the child component that I'm working with
That component's computed prop walks up its parent tree until it finds a component with a prop named model, containing name of "root". It assumes all parents have this prop, and fails otherwise, leading to the error you observed.
A workaround is to declare that property in your component before reading the computed prop:
export default {
props: {
👇
model: {
type: Object,
default: () => ({ name: 'root' }),
},
},
methods: {
test() {
const rootNode = this.$refs.tree.rootNode
console.log({ rootNode })
},
}
}
demo

Vue 3 Teleport for Vue 2

In Vue 3 it's possible to Teleport a component to the body tag like so:
<template>
<button #click="modalOpen = true">
Open full screen modal! (With teleport!)
</button>
<teleport to="body">
<div v-if="modalOpen" class="modal">
<div>
I'm a teleported modal!
(My parent is "body")
<button #click="modalOpen = false">
Close
</button>
</div>
</div>
</teleport>
</template>
<script>
export default {
data() {
return {
modalOpen: false
}
}
};
</script>
This causes the modal dialogue above to be rendered in the body tag. How can I achieve a similar thing in Vue 2?
Because Vue 2 doesn't support teleports, I recommend to use portal-vue component made for vue 2 :
Installation :
npm i portal-vue --save
Usage :
main.js
import Vue from "vue"
import PortalVue from 'portal-vue'
Vue.use(PortalVue)
...
inside some child component :
<portal to="destination">
<p>This slot content will be rendered wherever the <portal-target> with name 'destination'
is located.</p>
</portal>
in other place :
<portal-target name="destination">
<!--
This component can be located anywhere in your App.
The slot content of the above portal component will be rendered here.
-->
</portal-target

React pass ref throw functional components in different levels

I would like to scroll to menu element in a page.
I have the menu component which is not a parent of components to which I would like to scroll.
I have found this post that describe a similar problem
Passing ref to a child We want the ref to be attached to a dom element, not to a react component. So when passing it to a child
component we can't name the prop ref.
const myRef = useRef(null)
return <ChildComp refProp={myRef}></ChildComp> } ```
Then attach the ref prop to a dom element. ```jsx const ChildComp =
(props) => {
return <div ref={props.refProp} /> } ```
Here's my app structure
Menu component:
const MenuApp = () => {
return (
<div>
<div className="desktop-menu">
<div className="menu-item a-propos">
<p className='button'>Me découvrir</p>
</div>
<div className="menu-item competences">
<p className='button'>Compétences </p>
</div>
<div className="menu-item experiences">
<p className='button'>Experiences</p>
</div>
<div className="menu-item formation">
<p className='button'>Formation </p>
</div>
</div>
</div>
)
}
The parent is app component
<div className="App">
<div className="hero">
<HeaderApp />
<ApprochApp />
</div>
<Apropos />
<Competences />
<Experiences />
<Formation />
<Recom />
<Contact />
<Footer />
</div >
I would like that mu menus scrolls to the react components in the main App component
So how can I passe the reference from the menu component to the app and use it in components to scroll ?
I do not understand your problem completely though. However, one thing I can see from your question is that you're not forwarding the ref properly.
What you need in this case is forwardRef.
Basically, what you need to do is to create the childComponent as something like this:
const childComponent = React.forwardRef(({...otherProps}, ref) => {
return (<><div ref={ref}>Component content </div></>)
})
Where you need to use the component all you need to do is this:
const parentComponent = () => {
const reveiwsRef = React.useRef("");
return (
<div>
<childComponent ref={reviewsRef} />
</div>
);
}
You can find more info about this on the react documentation: Forwarding-Refs
I have hope this helps though

How to render component children at parent

I'm familiar with ReactJS, but not with VueJS.
Where can I place the component children at the parent component.
I have this example in ReactJS, how can I create the same using VueJs:
function FancyBorder(props) {
return (
<div className={'FancyBorder FancyBorder-' + props.color}>
{props.children}
</div>
);
}
function WelcomeDialog() {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
Welcome
</h1>
<p className="Dialog-message">
Thank you for visiting our spacecraft!
</p>
</FancyBorder>
);
}
What is the {props.children} in VueJS ??
The Vue analogy to the React "children" concept is the slots.
https://v2.vuejs.org/v2/guide/components.html#Content-Distribution-with-Slots
https://v2.vuejs.org/v2/guide/components-slots.html
Slots can be used like:
// FancyBorder.vue
<div class="FancyBorder">
<slot/>
</div>
// App.vue
<FancyBorder>
Contents!
</FancyBorder>
Vue slots also have an advantage over the React children, as you can have multiple "groups" of elements, using named slots, this can make the code less reliant on "magic" classnames:
// FancyBorder.vue
<div class="FancyBorder">
<h1 className="Dialog-title">
<slot name="header"></slot>
</h1>
<slot/>
</div>
// App.vue
<FancyBorder>
<template slot="header">
Header
</template>
Contents!
</FancyBorder>

Categories

Resources