Hay,
I want to create reuseable compoenent in React like for example DialogBox.
It has required fields like type, message and title.
Type can be one of 'yesNo' string or 'ok' and it defines how much buttons should be shown (yes & no, ok).
Message and title are simple text that are displayed inside of dialog box.
Simple view of this:
IMG
And I created DialogBox component that I can use like:
<DialogBox type={'yesNo'} message={'Message'} title={'Title'} />
But I want to use predefined const like that:
<DialogBox type={DialogBox.TYPE.YES_NO} message={'Message'} title={'Title'} />
With simple one import DialogBox:
import Dialogbox from './DialogBox.js'
To achieve DialogBox.TYPE.YES_NO
In my component DialogBox I created static object TYPE with predefined elements:
...
static TYPE = {
YES_NO: 'yesNo',
OK: 'ok'
}
...
And everything was beautiful to the time when I wanted to use that statics to check props in child component:
ButtonArea.propTypes = {
type: PropTypes.oneOf(Object.values(DialogBox.TYPE))
};
And I got a circular dependencies error and my DialogBox.TYPE inside of props definition is undefined. That is how I can see it:
In DailogBox.js :
import ButtonArea from './BA';
export default class DialogBox extends Component {
static TYPE = {
YES_NO: 'yesNo',
OK: 'ok'
}
render() {
<ButtonArea type={this.props.type} />
}
}
In ButtonArea.js:
import DialogBox from './DB';
export default class ButtonArea extends Component {...}
ButtonArea.propTypes = {
type: PropTypes.oneOf(Object.values(DialogBox.TYPE))
};
And on checking propTypes DialogBox is an undefined cause of circular dependencies.
The question is.
Is there a way to create component to use it like component and which has inside const object definitions and avoid circular dependencies. Like :
<Test type={Test.TYPE.SUPER_TEST}/>
I don't want to import Test and TestConst and use it like that:
<Test type={TestConst.TYPE.SUPER_TEST}/>
You need to update the propsType for button , you need to check for the KEYS instead of VALUES, like below
ButtonArea.propTypes = {
type: PropTypes.oneOf(Object.keys(DialogBox.TYPE))
};
Related
I want to extend the MUI5 components and also use their component prop. To do that according to the documentation I make it work in the below code:
import Button, { ButtonProps } from '#mui/material/Button';
import React from 'react';
export type MyButtonProps<C extends React.ElementType> = ButtonProps<C, { component?: C }> & {
myOtherField: string;
};
export function MyButton<C extends React.ElementType>(props: MyButtonProps<C>) {
const { myOtherField, ...buttonProps } = props;
return <Button {...buttonProps}></Button>;
}
However when I try to access anything belongs to MUI5 button attributes, vscode is not helping me to find it
see the below screenshot:
But after adding it manually it is not complaining about it.
see the below screenshot and check that it is inferring the type as any
However if I remove the <C extends React.ElementType> logic from the type it is working like a charm (but it has a drawback since it is now complaining about the component prop when I use it anywhere in my application):
What can be the problematic part in the first place when I am extending MUI5 button prop types?
thank you in advance.
This is the easy way I found for your usecase:
type NewButtonProps = ButtonProps & {
otherField: number;
component: React.ElementType;
};
function Button3({ otherField, ...props }: NewButtonProps) {
const y = props.onClick;
const x = otherField;
return <Button {...props}></Button>;
}
All the attributes is understand by typescript now:
While rewriting my VueJs project in typescript, I came across a TypeScript error.
This is a part of the component that has a custom v-model.
An input field in the html has a ref called 'plate' and I want to access the value of that. The #input on that field calls the update method written below.
Typescript is complaining that value does not exist on plate.
#Prop() value: any;
update() {
this.$emit('input',
plate: this.$refs.plate.value
});
}
template:
<template>
<div>
<div class="form-group">
<label for="inputPlate" class="col-sm-2 control-label">Plate</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPlate" ref="plate" :value="value.plate" #input="update">
</div>
</div>
</div>
</template>
You can do this:
class YourComponent extends Vue {
$refs!: {
checkboxElement: HTMLFormElement
}
someMethod () {
this.$refs.checkboxElement.checked
}
}
From this issue: https://github.com/vuejs/vue-class-component/issues/94
Edit - 2021-03 (Composition API)
Updating this answer because Vue 3 (or the composition API plugin if you're using Vue 2) has some new functions.
<template>
<div ref="root">This is a root element</div>
</template>
<script lang="ts">
import { ref, onMounted, defineComponent } from '#vue/composition-api'
export default defineComponent({
setup() {
const root = ref(null)
onMounted(() => {
// the DOM element will be assigned to the ref after initial render
console.log(root.value) // <div>This is a root element</div>
})
return {
root
}
}
})
</script>
Edit - 2020-04:
The vue-property-decorator library provides #Ref which I recommend instead of my original answer.
import { Vue, Component, Ref } from 'vue-property-decorator'
import AnotherComponent from '#/path/to/another-component.vue'
#Component
export default class YourComponent extends Vue {
#Ref() readonly anotherComponent!: AnotherComponent
#Ref('aButton') readonly button!: HTMLButtonElement
}
Original Answer
None of the above answers worked for what I was trying to do. Adding the following $refs property wound up fixing it and seemed to restore the expected properties. I found the solution linked on this github post.
class YourComponent extends Vue {
$refs!: {
vue: Vue,
element: HTMLInputElement,
vues: Vue[],
elements: HTMLInputElement[]
}
someMethod () {
this.$refs.<element>.<attribute>
}
}
son.vue
const Son = Vue.extend({
components: {},
props: {},
methods: {
help(){}
}
...
})
export type SonRef = InstanceType<typeof Son>;
export default Son;
parent.vue
<son ref="son" />
computed: {
son(): SonRef {
return this.$refs.son as SonRef;
}
}
//use
this.son.help();
This worked for me: use
(this.$refs.<refField> as any).value or (this.$refs.['refField'] as any).value
Avoid using bracket < > to typecast because it will conflict with JSX.
Try this instead
update() {
const plateElement = this.$refs.plate as HTMLInputElement
this.$emit('input', { plate: plateElement.value });
}
as a note that I always keep remembering
Typescript is just Javascript with strong typing capability to ensure type safety. So (usually) it doesn't predict the type of X (var, param, etc) neither automatically typecasted any operation.
Also, another purpose of the typescript is to make JS code became clearer/readable, so always define the type whenever is possible.
Maybe it will be useful to someone. It looks more beautiful and remains type support.
HTML:
<input ref="inputComment" v-model="inputComment">
TS:
const inputValue = ((this.$refs.inputComment as Vue).$el as HTMLInputElement).value;
In case of custom component method call,
we can typecast that component name, so it's easy to refer to that method.
e.g.
(this.$refs.annotator as AnnotatorComponent).saveObjects();
where AnnotatorComponent is class based vue component as below.
#Component
export default class AnnotatorComponent extends Vue {
public saveObjects() {
// Custom code
}
}
With Vue 3 and the Options API, this is what worked for me:
<script lang="ts">
import {defineComponent} from 'vue';
export default defineComponent({
methods: {
someAction() {
(this.$refs.foo as HTMLInputElement).value = 'abc';
},
},
});
</script>
The autocomplete doesn't bring the foo property from $refs because it's defined in the template, and apparently there's no information inferred from it.
However, once you force the casting of .foo to the HTML element type, everything works from there on, so you can access any element property (like .value, in the example above).
Make sure to wrap your exports with Vue.extend() if you are converting your existing vue project from js to ts and want to keep the old format.
Before:
<script lang="ts">
export default {
mounted() {
let element = this.$refs.graph;
...
After:
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
mounted() {
let element = this.$refs.graph;
...
I found a way to make it work but it is ugly in my opinion.
Feel free to give other/better suggestions.
update() {
this.$emit('input', {
plate: (<any>this.$refs.plate).value,
});
}
I spent a LONG time trying to find an answer to this using Vue 3, TypeScript with class components and (as it happens, although not relevant to this) TipTap. Found the answer from bestRenekton above which finally solved it, but it needed tweaking. I'm pretty sure this is TypeScript specific.
My child component has this at the start:
export default class WhealEditor extends Vue {
It includes this method (the one I want to call from the parent):
doThis(what: string) {
console.log('Called with ' + what)
}
And this right at the end:
export type EditorRef = InstanceType<typeof WhealEditor>
</script>
So this announces to any consumer of the child component that it can access it using the variable EditorRef. The parent component includes the child component in the template:
<WhealEditor ref="refEditor" />
The parent component then imports ref, and the child component and the exposed object:
import { ref } from 'vue'
import WhealEditor, { EditorRef } from './components/WhealEditor.vue'
I then have a method to get this object:
getEditor(): EditorRef {
// gets a reference to the child component
return this.$refs.refEditor as EditorRef
}
Finally, I can handle events - for example:
processButton(msg: string) {
// runs method in child component
this.getEditor().doThis(msg)
Like everything else to do with client script, it's so much harder than I expected!
While rewriting my VueJs project in typescript, I came across a TypeScript error.
This is a part of the component that has a custom v-model.
An input field in the html has a ref called 'plate' and I want to access the value of that. The #input on that field calls the update method written below.
Typescript is complaining that value does not exist on plate.
#Prop() value: any;
update() {
this.$emit('input',
plate: this.$refs.plate.value
});
}
template:
<template>
<div>
<div class="form-group">
<label for="inputPlate" class="col-sm-2 control-label">Plate</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPlate" ref="plate" :value="value.plate" #input="update">
</div>
</div>
</div>
</template>
You can do this:
class YourComponent extends Vue {
$refs!: {
checkboxElement: HTMLFormElement
}
someMethod () {
this.$refs.checkboxElement.checked
}
}
From this issue: https://github.com/vuejs/vue-class-component/issues/94
Edit - 2021-03 (Composition API)
Updating this answer because Vue 3 (or the composition API plugin if you're using Vue 2) has some new functions.
<template>
<div ref="root">This is a root element</div>
</template>
<script lang="ts">
import { ref, onMounted, defineComponent } from '#vue/composition-api'
export default defineComponent({
setup() {
const root = ref(null)
onMounted(() => {
// the DOM element will be assigned to the ref after initial render
console.log(root.value) // <div>This is a root element</div>
})
return {
root
}
}
})
</script>
Edit - 2020-04:
The vue-property-decorator library provides #Ref which I recommend instead of my original answer.
import { Vue, Component, Ref } from 'vue-property-decorator'
import AnotherComponent from '#/path/to/another-component.vue'
#Component
export default class YourComponent extends Vue {
#Ref() readonly anotherComponent!: AnotherComponent
#Ref('aButton') readonly button!: HTMLButtonElement
}
Original Answer
None of the above answers worked for what I was trying to do. Adding the following $refs property wound up fixing it and seemed to restore the expected properties. I found the solution linked on this github post.
class YourComponent extends Vue {
$refs!: {
vue: Vue,
element: HTMLInputElement,
vues: Vue[],
elements: HTMLInputElement[]
}
someMethod () {
this.$refs.<element>.<attribute>
}
}
son.vue
const Son = Vue.extend({
components: {},
props: {},
methods: {
help(){}
}
...
})
export type SonRef = InstanceType<typeof Son>;
export default Son;
parent.vue
<son ref="son" />
computed: {
son(): SonRef {
return this.$refs.son as SonRef;
}
}
//use
this.son.help();
This worked for me: use
(this.$refs.<refField> as any).value or (this.$refs.['refField'] as any).value
Avoid using bracket < > to typecast because it will conflict with JSX.
Try this instead
update() {
const plateElement = this.$refs.plate as HTMLInputElement
this.$emit('input', { plate: plateElement.value });
}
as a note that I always keep remembering
Typescript is just Javascript with strong typing capability to ensure type safety. So (usually) it doesn't predict the type of X (var, param, etc) neither automatically typecasted any operation.
Also, another purpose of the typescript is to make JS code became clearer/readable, so always define the type whenever is possible.
Maybe it will be useful to someone. It looks more beautiful and remains type support.
HTML:
<input ref="inputComment" v-model="inputComment">
TS:
const inputValue = ((this.$refs.inputComment as Vue).$el as HTMLInputElement).value;
In case of custom component method call,
we can typecast that component name, so it's easy to refer to that method.
e.g.
(this.$refs.annotator as AnnotatorComponent).saveObjects();
where AnnotatorComponent is class based vue component as below.
#Component
export default class AnnotatorComponent extends Vue {
public saveObjects() {
// Custom code
}
}
With Vue 3 and the Options API, this is what worked for me:
<script lang="ts">
import {defineComponent} from 'vue';
export default defineComponent({
methods: {
someAction() {
(this.$refs.foo as HTMLInputElement).value = 'abc';
},
},
});
</script>
The autocomplete doesn't bring the foo property from $refs because it's defined in the template, and apparently there's no information inferred from it.
However, once you force the casting of .foo to the HTML element type, everything works from there on, so you can access any element property (like .value, in the example above).
Make sure to wrap your exports with Vue.extend() if you are converting your existing vue project from js to ts and want to keep the old format.
Before:
<script lang="ts">
export default {
mounted() {
let element = this.$refs.graph;
...
After:
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
mounted() {
let element = this.$refs.graph;
...
I found a way to make it work but it is ugly in my opinion.
Feel free to give other/better suggestions.
update() {
this.$emit('input', {
plate: (<any>this.$refs.plate).value,
});
}
I spent a LONG time trying to find an answer to this using Vue 3, TypeScript with class components and (as it happens, although not relevant to this) TipTap. Found the answer from bestRenekton above which finally solved it, but it needed tweaking. I'm pretty sure this is TypeScript specific.
My child component has this at the start:
export default class WhealEditor extends Vue {
It includes this method (the one I want to call from the parent):
doThis(what: string) {
console.log('Called with ' + what)
}
And this right at the end:
export type EditorRef = InstanceType<typeof WhealEditor>
</script>
So this announces to any consumer of the child component that it can access it using the variable EditorRef. The parent component includes the child component in the template:
<WhealEditor ref="refEditor" />
The parent component then imports ref, and the child component and the exposed object:
import { ref } from 'vue'
import WhealEditor, { EditorRef } from './components/WhealEditor.vue'
I then have a method to get this object:
getEditor(): EditorRef {
// gets a reference to the child component
return this.$refs.refEditor as EditorRef
}
Finally, I can handle events - for example:
processButton(msg: string) {
// runs method in child component
this.getEditor().doThis(msg)
Like everything else to do with client script, it's so much harder than I expected!
In the Creating a component section of React Typescript Starter example, Creating a component, there is a basic React component in Typescript:
// src/components/Hello.tsx
import * as React from 'react';
export interface Props {
name: string;
enthusiasmLevel?: number;
}
function Hello({ name, enthusiasmLevel = 1 }: Props) {
if (enthusiasmLevel <= 0) {
throw new Error('You could be a little more enthusiastic. :D');
}
return (
<div className="hello">
<div className="greeting">
Hello {name + getExclamationMarks(enthusiasmLevel)}
</div>
</div>
);
}
export default Hello;
// helpers
function getExclamationMarks(numChars: number) {
return Array(numChars + 1).join('!');
}
I am new to Typescript. It seems that the interface Props is used by Typescript to do props type checks (similar to what the Proptypes npm package does). So the question is:
If I am already using this kind of Typescript
interface syntax do to props type check, do I still need to use
Proptypes package like this in the same component?
import PropTypes from 'prop-types';
Hello.propTypes = {
name: PropTypes.string,
enthusiasmLevel: PropTypes.number
};
Besides, why does here use export interface? what is the purpose
of exporting the interface Props? Is it compulsory?
Firstly I recommend declaring your components the ES6 way
const Hello: React.FC<IHello> = ({ name, enthusiasmLevel = 1 }) => {}
Your interface defines the contract of your component / The accepted parameters
export interface IHello {
name: string;
enthusiasmLevel?: number;
}
You are exporting this, so you can import your interface from other files / components which want to make use of the Hello component. For example you can use your Hello component like so from another component:
const props: IHello = {
name: "John",
enthusiamsLevel: 5
}
<Hello {...props} />
If I am already using this kind of Typescript interface syntax do to props type check, do I still need to use Proptypes in the same component?
You always want type strong definitions in TypeScript. So when declaring your prop variable in another component, you don't want to do const props: any = {
If you decide to change your interface declaration for this component later on, you would be forced to update all your references which uses this interface. - You might want to require 1 more prop variable and in that case you would want to update your usages of this interface. If you are not used to TypeScript this can seem quite hideous at first - but the benefit of always having strong type definitions will show over time. Especially when you update your type definitions.
So let's just say that I have a HelloWorld component that I would like to import multiple times and assign some props to each one (as each instance will be doing their own thing). Usually you'll do something like this:
To keep it simple I haven't used proper syntax.
import HelloWorld from "./components/HelloWorld";
<HelloWorld v-if="which" title="0" key="1"/>
<HelloWorld v-else title="1"/>
However, I was wondering if there was a way to import them with props already assigned so something like:
import HelloWorld from "./components/HelloWorld";
import HelloWorld1 from "./components/HelloWorld";
HelloWorld.props = { title: "1" } // this doesn't work
HelloWorld1.props = { title: "2" } // this doesn't work
In order to use <component>
E.g.
<component :is="which"/>
which = "HelloWorld" || "HelloWorld1"
A component's props can only be set in the component definition object.
It looks like you're attempting to pass different prop values based on the value of which. You can do that by passing an object to v-bind:
<HelloWorld v-bind="which ? { title: '0', key: '1' } : { title: '1' }"/>