I want to create my static variables outside of my component and then call and using it in my component.
Btw i dont want outside variables as a component or props.
You can create class like that
export default class TableConst {
static LocaleText = {
values: {
to: "-",
page: " ",
}
};
}
Then import that static class and use it in your main page
import TableConst from "../TableConst";
...
...
...
let columnDefs={TableConst.LocaleText.values}
If you define variable inside the class using a static keyword you can access those variable using class Name directly without instantiating it.
class CustomVariables {
static MyVariable = 'SomeContent';
static MyVariable2 = 'SomeContent2';
}
export default CustomVariables;
Also you could write those variables within the class and return an instance of the class
class CustomVariables {
constructor() {
this.MyVariable = 'SomeContent';
this.MyVariable2 = 'SomeContent2';
}
}
export default CustomVariables();
and you can use it like below for both the caes
import CustomVariables from 'path/to/CustomVariables';
console.log(CustomVariables.MyVariable)
Related
I'm building a React app with an embedded Google Map.
I've got a custom menu element that I want to display on the map after a click. Google's docs instruct me to 'implement' (although I think in Typescript terms, they mean extend) the google.maps.OverlayView class in order to render elements over the map.
When I define the class ContextMenu extends google.maps.OverlayView class inline, the code compiles fine and my element shows up on click. I want to define this class in a separate file, using Typescript.
However, when I move ContextMenu to a separate file, React errors out with ReferenceError: google is not defined.
Any idea how to 'import the namespace' such that ContextMenu.ts knows where google is? It seems like I am missing something fundamental about Typescript here, but none of their documentation I've been able to find has discussed the practice of creating classes with external namespaces.
Or is extends the wrong way to do this here? Should I just follow Google's instructions, even in Typescript which exists to avoid messing with prototypes?
Inherit from this class by setting your overlay's prototype: MyOverlay.prototype = new google.maps.OverlayView();.
Working code:
// App.tsx
import React from 'react'
import { Wrapper } from '#googlemaps/react-wrapper'
// cannot define ContextMenu here
const App: React.VFC = () => {
// cannot define ContextMenu here
const onClick = (e: google.maps.MapMouseEvent) => {
// CAN define ContextMenu here
class ContextMenu extends google.maps.OverlayView {
private origin_: google.maps.LatLng
constructor(origin: google.maps.LatLng) {
super()
this.origin_ = origin
}
}
const menu = new ContextMenu(e.latLng)
}
return (
<Wrapper ...>
// Map goes here
</Wrapper>
)
}
Broken code:
// App.tsx as above, without ContextMenu defined.
// ContextMenu.ts
class ContextMenu extends google.maps.OverlayView {
// ...
}
It is not possible to directly extend a google.maps.* class since it actually isn't available (this might depend on tsconfig target, but I haven't tested). You can use the following pattern in TypeScript to delay.
export interface OverlayViewSafe extends google.maps.OverlayView {}
/**
* Extends an object's prototype by another's.
*
* #param type1 The Type to be extended.
* #param type2 The Type to extend with.
* #ignore
*/
// eslint-disable-next-line #typescript-eslint/no-explicit-any
function extend(type1: any, type2: any): void {
// eslint-disable-next-line prefer-const
for (let property in type2.prototype) {
type1.prototype[property] = type2.prototype[property];
}
}
/**
* #ignore
*/
export class OverlayViewSafe {
constructor() {
// We use the extend function for google.maps.OverlayView
// because it might not always be available when the code is defined.
extend(OverlayViewSafe, google.maps.OverlayView);
}
}
car.ts has "isNewCar" variable in "export class Car{}", and I need to export the "isNewCar" variable to another component carSale.ts which is in a different directory, and not in the same module. Do I have to add the car.ts template to the carSale.ts file and add the "isNewCar" as input?
edit: car.ts has export class Car{ isNewCar:boolean = false; } and car.ts is a component. carSale.ts is also a component but it is not in a same/shared module as car.ts I need carSale.ts, and eventually carSale.ng.html to get access to the isNewCar variable. So, can you tell me how I would use the viewChild decorator or anything else in carSale.ts to access that variable? I would ideally not want to make a shared module though but if I have to, I can.
you can extend the Car class like,
export class CarSale extends Car {
ngOnInit(){
this.isNewCar = true;
}
}
By extending the Car class, you will be able to access the isNewCar property from the CarSale class
Need some more information about the use case. Is the car.ts a component or a model ?
If the car.ts is a model you should aggregate it in your carSale.ts component or, if really necesary, make it globaly available with a service.
If car.ts is a component with his own template, then you can acces the value with the output event emitter or by using a viewChild decorator.
There are other way to share variables but the above is the more common.
car.ts :
/*
* This is a POJO
*/
export class Car{
isNew: boolean;
}
car-sale.component.ts :
export class CarSale {
car: Car; // Car is aggregate into CarSale
ngOnInit(){
car = new Car();
car.isNew = true;
}
}
car-sale.component.html
<-- just use your car object like this --!>
<div *ngIf="car">Is the car new ? {{ car.isNew }}</div>
I'm trying to migrate my class based component to functional component.
keep getting struggles on change getter / static methods , how can I achieve these?
// class based component
class Example extends Component {
...
flag = Math.random * 1 + 1;
get someGetter(){
return flag
}
usingGetter(){
if(this.someGetter) console.log("using Getter called! ");
}
static someStatic(){
console.log("this is some static function" );
}
...
}
just convert it to normal variable, you dont need it as class member
const someGetter = () => flag
usingGetter () {
if (someGetter()) console.log("using Getter called! ");
}
To be clear, I am learning TypeScript and React for spfx developments. I have read and taken part in tutorials and other answers on various sources and Stack Overflow and haven't found them enough to help me.
Here is my function in the EvalReqNewForm class (getGrades()):
export default class EvalReqNewForm extends React.Component<IEvalReqNewProps, IEvalReqNewState> {
constructor(props){
super(props);
this.state = {
EvalType: null,
JobTitReportTo: null,
JobTitReportToNum: null,
PropGradeList: [],
SelectedGrade: undefined,
CompPos: null,
ContextNewJobCode: null
};
this._onJobTitReportToChange = this._onJobTitReportToChange.bind(this);
this._onJobTitReportToNumChange = this._onJobTitReportToNumChange.bind(this);
this._onPropGradeChange = this._onPropGradeChange.bind(this);
}
...
public _getGrades() {
pnp.sp.web.lists.getByTitle("Grades").items.get().then((items: any[]) =>{
let returnedGrades:IDropdownOption[]= items.map((item) =>{return {key:item.Title, text:item.Title};});
this.setState({PropGradeList : returnedGrades});
});
}
And I want to use the _getGrades() function from the other class to use in a ComponentDidMount() in order to the 'Grades' from the SP list.
Does it involve using props? Or can the function be simply exported and imported into the class where I want to use it?
Please understand I'm learning the basics here!
TL;DR
Create a function that only depends on it's parameters and export/import it.
Or can the function be simply exported and imported into the class where I want to use it?
What you can do is create a function that depends only on it's parameters.
So it would be something like
export function getGrades(something){
// do what ever you want with something
return somethingYouDid
}
And then you import it to other files and use it like
import { getGrades } from '...'
...
public _getGrades() {
const results = getGrades(someDataFromSomeWhere)
this.setState({PropGradeList : results});
}
I also see that you are using promises, so maybe you will need to use async/await in your case.
Edit:
As said in the comments
I can't seem to use export within a class
You should use it out side of the class, you will have to functions.
One out side of the class that have all the logic and other inside that class that only calls the outside function.
export function getGrades(something){
// do what ever you want with something
return somethingYouDid
}
class ... {
...
public _getGrades() {
const results = getGrades(someDataFromSomeWhere)
this.setState({PropGradeList : results});
}
}
I am new to typescript my code is not showing compile error if passing the wrong type to parameter of method. My code is something like this:-
export interface empData {
empName:string;
}
export class Employee implements empData
{
empName:string;
constructor(empName:string){
this.empName=empName;
}
Now I want to use the Employee class as the datatype for that I
created one function in separate file and write method as:-
export function showName(empName:Employee){
return empName;
}
Now in my component I am passing showName as props using redux and
connect method
export default class EmployeeDetail extends React.Component{
//now I am trying to call the function
showEmp(){
this.props.showName('');
}
}
this.props.showName(' ') this call not showing any type error, ideally
it should pass as this.props.showName(new
Employee({empName='someName'}); Please assist me What I am doing
mistake. How can I make my code typesafe.In above example I want the
method parameter should be type safe by the Employee object.
React.Component is generic, it's first generic parameter is the type of props. You can use an anonymous interface, or a named interface as a parameter, and this will trigger the compiler to perform the apropriate checks:
class EmployeeDetail extends React.Component<{ showName: (empName: Employee) => Employee}> {
//now I am trying to call the function
showEmp() {
this.props.showName(''); //error
}
}
//OR
interface EmployeeDetailProps { showName: (empName: Employee) => Employee}
class EmployeeDetail extends React.Component<EmployeeDetailProps> {
//now I am trying to call the function
showEmp() {
this.props.showName(''); //error
}
}
// Usage
let d = <EmployeeDetail showName={showName} />