Last active
January 31, 2022 05:51
-
-
Save tomstorms/8b7e808c36f1beb5f528e20f12f4ddd8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#----------------------------------------------------- | |
# Destructure your props: | |
before: | |
<DismissArea | |
visible={visible} | |
setVisible={setVisible} | |
onPress={onPress} | |
/> | |
after: | |
<DismissArea | |
{ ... { visible, setVisible, onPress}} | |
/> | |
#----------------------------------------------------- | |
# Access a property of an object with a variable: | |
const car = { | |
color: "red", | |
style: "sedan", | |
isRegistered: true | |
} | |
const x = "color" | |
console.log(car[x]) | |
// "red" | |
#----------------------------------------------------- | |
# "This expression is not callable": | |
return [open, toggle, setOpen] as const; | |
#----------------------------------------------------- | |
# Cant use break or return on map. Use a for loop instead: | |
for (var i = 0; i < myArray.length; i++) { | |
// const item = myArray[i]; | |
} | |
#----------------------------------------------------- | |
# useRef | |
const componentContainer = useRef<HTMLDivElement>(null!); | |
... | |
<div ref={componentContainer}></div> | |
#----------------------------------------------------- | |
# useState | |
const [containerWidth, setContainerWidth] = useState(''); | |
... | |
setContainerWidth('400px') | |
<div style={{ | |
width: containerWidth | |
}}></div> | |
#----------------------------------------------------- | |
# useEffect for window hooks | |
# make sure you specify the [] in useEffect | |
# also make sure you return() => {} in useEffect to clean up | |
function setContainerWidth() { | |
const screenWidth = window.innerWidth; | |
if (screenWidth > 976 && componentContainer.current) { | |
const componentWidth = componentContainer?.current.clientWidth; | |
const diffWidth = ((screenWidth - componentWidth) / 2); | |
const vWrapperWidth = videoWrapper.current.clientWidth + 48; // 48 = 3rem (.gap-12) | |
const responsiveVideoWrapperWidth = (vWrapperWidth + diffWidth); | |
setContainerWidth(responsiveVideoWrapperWidth + 'px') | |
} | |
else { | |
setContainerWidth('') | |
} | |
} | |
useEffect(() => { | |
if (document.readyState === "complete") { | |
// Call if React app already loaded | |
setContainerWidth(); | |
// Add hooks if page access directly | |
window.addEventListener('load', setContainerWidth); | |
window.addEventListener('resize', setContainerWidth); | |
} | |
else { | |
// Add hooks if page access directly | |
window.addEventListener('load', setContainerWidth); | |
window.addEventListener('resize', setContainerWidth); | |
} | |
return () => { | |
// Cleanup | |
console.log('cleaning up'); | |
window.removeEventListener('load', setContainerWidth); | |
window.removeEventListener('resize', setContainerWidth); | |
} | |
}, []); | |
#----------------------------------------------------- | |
# Div background | |
<div style={{ | |
backgroundImage: "url(" + `${data?.image.url}` + ")", | |
}}></div> | |
#----------------------------------------------------- | |
# Map | |
const articles = ['articleObj1', 'articleObj2', 'articleObj3'] | |
{ articles && articles.map((article : any, i : number) => { | |
return ( | |
<div key={i}>El</div> | |
) | |
})} | |
#----------------------------------------------------- | |
# Filter | |
const categoryArticles = data.articles.filter((article : any) => { | |
return (article.article_category.category_slug === slug); // must return true to be included in list | |
}); | |
#----------------------------------------------------- | |
# Add to array - typescript happy | |
var articles : any = []; | |
articles.push(article); | |
#----------------------------------------------------- | |
# Combine arrays | |
const array1 = [1,2]; | |
const array2 = [3,4]; | |
const array3 = array1.concat(array2); | |
#----------------------------------------------------- | |
# Look into an array, find an element, change it false, then return an array | |
const data = prevState.data.map(item => (item.isVisible === true) ? (item.isVisible = false, item) : item); | |
#----------------------------------------------------- | |
# Replace an element of an array | |
const index = prevState.data.findIndex((e) => e.id === selectedLocationId); | |
prevState.data[index].isVisible = !prevState.data[index].isVisible; // eslint-disable-line no-param-reassign | |
#----------------------------------------------------- | |
# Allow async in function | |
export const getStaticProps = async () => { | |
const propsData = await getStaticPropsForPages('home'); | |
return { | |
props: { | |
pageData: propsData | |
} | |
} | |
} | |
#----------------------------------------------------- | |
# Deep clone object | |
let newObject = JSON.parse(JSON.stringify(object)); | |
#----------------------------------------------------- | |
# Random string generation | |
let randId = () => { | |
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10); | |
} | |
#----------------------------------------------------- | |
# interface props on components | |
interface ItemProps { | |
name?: string | |
size?: "lg" | "md" | "sm" | |
disabled?: boolean | |
[propName: string]: any | |
} | |
const Item: React.FC<ItemProps> = (props) => { | |
const { | |
as = "Item", | |
children, | |
className, | |
disabled = false, | |
size = "md", | |
name, | |
...otherProps | |
} = props | |
... | |
} | |
#----------------------------------------------------- | |
# Typescript interfaces | |
interface TagProps { | |
type?: "stat" | "icon" | "token" | "figure" // optional with different types | |
name: string // required field (without ?) | |
img: { | |
src: string | |
alt: string | |
} | |
articles: ArticleProps[] // reference a list of another interface | |
article: ArticleProps | |
[propName: string]: any // wildcard | |
onClick?: () => void // function with void return type | |
ref: Ref<HTMLElement> | |
) | |
export type Fruit = "Orange" | "Apple" | "Banana"; | |
let myString: string = "Banana"; | |
let myFruit: Fruit = myString as Fruit; | |
#----------------------------------------------------- | |
# Const variations | |
const { "json-node": pageData } = pageContent // read the json-node data from pageContent variable and use it as a "pageData" variable | |
#----------------------------------------------------- | |
# inline html tag | |
<div className={className || undefined}> | |
#----------------------------------------------------- | |
# Deconstructing variables | |
const { data } = useCustomHook() | |
const { status } = (data as CustomDataInterface) || {} | |
#----------------------------------------------------- | |
# Async UseEffect | |
useEffect(() => { | |
(async () => { | |
const data = await fetchList(); | |
setListData(data); | |
})(); | |
}); | |
#----------------------------------------------------- | |
# Example of preventing memory leaks | |
function Example() { | |
const [vehicles, setVehicles] = useState([]) | |
const vehiclesRef = collection(db, 'vehicles') | |
useEffect(() => { | |
let isMounted = true | |
const getVehicles = async () => { | |
const data = await getDocs(vehiclesRef) | |
if(isMounted){ | |
setVehicles(data.docs.map( doc => ( | |
{ | |
...doc.data(), | |
id:doc.id | |
} | |
) | |
) | |
) | |
} | |
} | |
getVehicles() | |
console.log(vehicles) | |
return () => { isMounted = false } | |
}, [vehicles]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment