-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathReact.js
2828 lines (2425 loc) · 74.1 KB
/
React.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// REACT - Javascript Library - by Beumsk
/**/
// REACT FRAMEWORKS
// create-react-app -> 1st party; simple and basic; it is opinionated; many dependencies that could be useless
// next.js -> ssr or ssg; very fast; integrates best with Vercel hosting which costs
// gatsby -> very fast; plugins and themes available; hard to migrate; official gatsby hosting costs
// blitz -> not very established; good doc but not for migration; fast even with API query; needs a server (except on Vercel)
// redwood -> not very established; JAM stack; tricky migration; deploy everywhere; meant to be serverless
// remix -> very recent
// start a new react project with a builder
create-react-app project-name
create-react-app project-name --template typescript // to have typescript set up
npm start
// FUNCTIONAL COMPONENTS
// state, ref and lyfecycle arrived in react v16.8 with hooks
// still can't use componentDidError and getSnapshotBeforeUpdate
// React Components
const FunctionalComponent() {
return <h1>Hello world</h1>;
};
const FunctionalComponent = () => (
<h1>Hello world</h1>;
);
// React Component multiline
const FunctionalComponent() {
return (
<div>
<h1>Hello world</h1>
<p>How you doing?</p>
</div>
);
}
const FunctionalComponent = () => (
<div>
<h1>Hello world</h1>
<p>How you doing?</p>
</div>
);
// Render Component
import React from "react";
const FunctionalComponent = () => { return <h1>Hello world</h1>; };
ReactDOM.render(<FunctionalComponent />, document.getElementById('app'));
// OR
import React from "react";
const FunctionalComponent = () => { return <h1>Hello world</h1>; };
export default FunctionalComponent;
// OR
import React from "react";
export default function FunctionalComponent() { return <h1>Hello world</h1>; };
// Pay attention to the export method !!!
export default function ComponentName() {};
import ComponentName from './path';
const ComponentName = () => {};
export default ComponentName;
import ComponentName from './path';
export function ComponentName() {};
import { ComponentName } from './path';
export const ComponentName = () => {};
import { ComponentName } from './path';
// PROPS
import PropTypes from 'prop-types'; // needs 'npm install prop-types'
const FunctionalComponent = (props) => {
return <h1>Hello, {props.name}</h1>;
};
// OR
const FunctionalComponent = ({ name }) => {
return <h1>Hello, {name}</h1>;
};
// OR
const FunctionalComponent = ({ name, ...props }) => {
return <h1>Hello, {name} {props.surname}</h1>;
};
// prop types arrayOf(number), objectOf(string)) -> https://reactjs.org/docs/typechecking-with-proptypes.html
FunctionalComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
fun: PropTypes.bool,
arr: PropTypes.array,
obj: PropTypes.obj,
el: PropTypes.element,
one: PropTypes.oneOf([number, string])
};
// default props
FunctionalComponent.defaultProps = { age: 16 };
<FunctionalComponent name="John" age={25} fun={true} arr={[1, 2]} obj={{yes: 'no'}} el={<AnotherComponent />} one={1} />
// PROPS FROM PARENT TO CHILD
import { ChildComponent } from './ChildComponent';
const ParentComponent = () => {
return <ChildComponent name="John" />;
};
export const ChildComponent = ({ name, ...props }) => {
return <h1>Hello, {name}</h1>
};
// PROPS FROM CHILD TO PARENT
import { ChildComponent } from './ChildComponent';
const ParentComponent = () => {
const getFromChild = (data) => {
console.log(data);
}
return <ChildComponent func={getFromChild} />;
};
export const ChildComponent = ({ func, ...props }) => {
func('This is data')
return <></>
};
// STATE HOOK
import { useState } from 'react';
const FunctionalComponent = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>count: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
{/* better way to use current state */}
<button onClick={() => setCount(curr => curr + 1)}>+</button>
</div>
);
};
// OR conditional rendering based on state
const FunctionalComponent = () => {
const [show, setShow] = useState(false);
return (
<div>
<button onClick={() => setShow(!show)}>{show ? 'Hide' : 'Show'}</button>
{show && <p>{show ? `Ì'm visible` : `Ì'm not visible`}</p>}
</div>
);
};
// EFFECT HOOK
import { useEffect } from 'react';
const FunctionalComponent = () => {
// On Mounting
useEffect( () => console.log("mount"), [] );
// update specific data
useEffect( () => console.log("will update data"), [ data ] );
// update all
useEffect( () => console.log("will update any") );
// update specific data on unmount
useEffect( () => () => console.log("will update data on unmount"), [ data ] );
// On Unmounting
useEffect( () => () => console.log("unmount"), [] );
// updated data returned
return <h1>{data}</h1>;
};
// skip first render with useEffect
import { useEffect, useRef } from 'react';
const FunctionalComponent = () => {
// useref to avoid wasted renders
const notInitialRender = useRef(false)
useEffect(() => {
if (notInitialRender.current) {
// do your magic here
} else {
notInitialRender.current = true
}
}, [data])
return <h1>{data}</h1>;
}
// REF HOOK
import { useRef } from 'react';
const FunctionalComponent = () => {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
// REDUCER HOOK
// useReducer instead of useState for complex state logic
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
const FunctionalComponent = () => {
const [state, dispatch] = useReducer(reducer, {count: 0});
return (
<div>
<p>count: {state.count}</p>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</div>
);
};
// MEMO HOOK
// lets you cache the result of a calculation between re-renders.
import { useMemo } from 'react';
const memoizedValue = useMemo(
() => computeExpensiveValue(a, b),
[a, b]
);
// CALLBACK HOOK
// lets you cache a function definition between re-renders.
import { useCallback } from 'react';
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);
// CONTEXT HOOK
// very useful to pass data deep in the tree
import { createContext, useState } from 'react';
export const CountContext = createContext();
const FunctionalComponent = () => {
const [count, setCount] = useState(0);
return (
<CountContext.Provider value={{setCount, count}}>
<ChildComponent />
</CountContext.Provider>
)
}
import { useContext } from 'react';
import { CountContext } from './FunctionalComponent';
const ChildComponent = () => {
const {setCount, count} = useContext(CountContext);
return (
<div>
<p>count: {count}</p>
<button onClick={() => setCount(count + 1)}>Click</button>
</div>
)
}
// ID HOOK
// very useful to have unique IDs generated for similar elements
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
return (
<>
<label>
Password:
<input type="password" aria-describedby={passwordHintId} />
</label>
<p id={passwordHintId}>The password should contain at least 18 characters</p>
</>
);
}
export default function App() {
return (
<>
<h2>Choose password</h2>
<PasswordField />
<h2>Confirm password</h2>
<PasswordField />
</>
);
}
// PORTAL
// creates node out of parent; body or anywhere else
import { useState } from 'react';
import { createPortal } from 'react-dom';
export default function Modal() {
const [showModal, setShowModal] = useState(false);
return (
<>
<button onClick={() => setShowModal(true)}>Open modal</button>
{showModal &&
createPortal(
<div className="modal">
<h2>Modal title</h2>
<button onClick={() => setShowModal(false)}>Close</button>
</div>,
document.body
)}
</>
);
}
// EVENTS
const EventComponents = () => (
<>
<button onCLick={}>btn</button>
<button onContextMenu={}>btn</button>
<button onDoubleClick={}>btn</button>
<button onMouseOver={}>btn</button>
<button onMouseOut={}>btn</button>
<button onChange={}>btn</button>
<button onSubmit={}>btn</button>
<button onFocus={}>btn</button>
<button onBlur={}>btn</button>
<button onKeyDown={}>btn</button>
<button onKeyPress={}>btn</button>
<button onKeyUp={}>btn</button>
<button onCopy={}>btn</button>
<button onCut={}>btn</button>
<button onPaste={}>btn</button>
{/* and many more -> https://reactjs.org/docs/events.html */}
</>
)
// FORMS (controlled, react manage the state of the form)
import { useState } from 'react';
const ControlledInput = () => {
const [input, setInput] = useState('');
const [textarea, setTextarea] = useState('');
const [select, setSelect] = useState(1);
const [checkbox, setCheckbox] = useState(false);
const [radio, setRadio] = useState(false);
const [radioString, setRadioString] = useState('');
function handleChange(e) {
setInput(() => e.target.value);
}
return (
<div>
<form>
<label htmlFor="input">Name:</label>
<input id="input" type="text" name="name" value={input} onChange={handleChange} />
{/* external OR inline onChange function */}
<input value={input} onChange={(e) => setInput(e.target.value)} />
<textarea value={textarea} onChange={(e) => setTextarea(e.target.value)} />
<select value={select} onChange={(e) => setSelect(e.target.value)}>
<option value={1}>1</option>
<option value={2}>2</option>
</select>
<input type="checkbox" checked={checkbox} onChange={(e) => setCheckbox(e.target.checked)} />
<input type="radio" checked={radio} onChange={(e) => setRadio(e.target.checked)} />
<input type="radio" checked={radio} value="radio-string" onChange={(e) => setRadioString(e.target.value)} />
</form>
<p>Input value: {input}</p>
<p>Textarea value: {textarea}</p>
<p>Select value: {select}</p>
<p>Checkbox value: {checkbox.toString()}</p>
<p>Radio value: {radio.toString()}</p>
</div>
)
};
// FORMS (simplified state)
import { useState } from 'react';
const ControlledInput = () => {
const [form, setForm] = useState({
name: "John",
surname: "Doe",
desc: "Newbie dev"
});
function handleChange(e) {
setForm((curr) => ({...curr, [e.target.name]: e.target.value}));
}
return (
<div>
<form>
<input type="text" name="name" value={form.name} onChange={handleChange} />
<input type="text" name="surname" value={form.surname} onChange={handleChange} />
<textarea name="desc" value={form.desc} onChange={handleChange} />
</form>
<p>Name: {form.name}</p>
<p>Surname: {form.surname}</p>
<p>Desc: {form.desc}</p>
</div>
)
};
// 'react-hook-form' to build forms faster (uncrontrolled forms & more performance)
import { useForm } from "react-hook-form";
function ReactHookForm() {
const { register, handleSubmit, watch, formState: { errors } } = useForm();
const onSubmit = data => console.log(data);
console.log(watch("example")); // watch input value by passing the name of it
return (
/* "handleSubmit" will validate your inputs before invoking "onSubmit" */
<form onSubmit={handleSubmit(onSubmit)}>
{/* register your input into the hook by invoking the "register" function */}
<input defaultValue="test" {...register("example")} />
{/* include validation with required or other standard HTML validation rules */}
<input {...register("exampleRequired", { required: true })} />
{/* errors will return when field validation fails */}
{errors.exampleRequired && <span>This field is required</span>}
<input type="submit" />
</form>
);
}
// 'formik' to build forms faster (controlled forms)
import { Formik, Field, Form } from "formik";
function FormikForm() {
return (
<Formik
initialValues={{ name: "", email: "" }}
onSubmit={async (values) => {
await new Promise((resolve) => setTimeout(resolve, 500));
alert(JSON.stringify(values, null, 2));
}}
>
<Form>
<Field name="name" type="text" />
<Field name="email" type="email" />
<button type="submit">Submit</button>
</Form>
</Formik>
);
}
// 'yup' helps with validation
import * as yup from 'yup';
const schema = Yup.object().shape({
name: yup.string().min(2, 'Too short').required('Required'),
email: yup.string().email('Invalid email').required('Required')
});
// FORM (uncrontolled, DOM manage the form)
import React, { useRef, useState } from "react";
const UncontrolledInput = () => {
const fileInput = useRef("");
const [fileName, setFileName] = useState("");
const func = () => {
setFileName(fileInput.current.value);
};
return (
<>
<input type="file" ref={fileInput} />
<button onClick={func}>Upload file</button>
{fileName && <p>You uploaded {fileName}</p>}
</>
);
};
// ERROR BOUNDARIES
// https://reactjs.org/docs/error-boundaries.html
// HANDLING ERRORS and async
import { useEffect, useState } from 'react';
const FunctionalComponent = () => {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState("");
// fake data fetching
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
useEffect(() => {
async function delayFunc() {
try {
// fetch data
await delay(2000);
setIsLoading(false);
setData(["waw"]);
}
catch (e) {
setIsLoading(false);
setError(e);
}
}
delayFunc();
}, []);
if (error) return <p>Loading failed: {error}</p>
if (isLoading) return <p>Loading...</p>
return (
<p>{data}</p>
)
}
// ROUTING with react router dom !!very much different in V6
// install react-router-dom (yarn or npm)
// V6 basics
import { BrowserRouter, Routes, Route } from "react-router-dom";
const FunctionalComponent = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}>
<Route index element={<Home />} />
<Route path="blog">
<Route path=":id" element={<BlogPost />} />
<Route index element={<Blog />} />
</Route>
<Route path="about" element={<About />} />
</Route>
<Route path="*" element={<PageNotFound />} />
</Routes>
</BrowserRouter>,
)
}
// V5 basics
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
// import different page components
const FunctionalComponent = () => {
return (
<Router>
<Switch>
<Route path="/" exact>
<Home />
</Route>
<Route path="/blog">
<Blog />
</Route>
<Route path="/blog/:title">
<BlogPost />
</Route>
<Route >
<PageNotFound />
</Route>
</Switch>
</Router>
);
};
// Link and NavLink
import { Link, NavLink } from 'react-router-dom';
const FunctionalComponent = () => {
return (
<nav>
<NavLink to="/" style={isActive => ({color: isActive ? 'red' : ''})}>Home</NavLink>
<Link to="/">Blog</Link>
</nav>
)
};
// navigate
import ( useNavigate ) from 'react-router-dom';
const navigate = useNavigate();
const FunctionalComponent = () => {
return (
<>
<button onClick={() => navigate('/')}>Go Root</button>
{/* navigate and pass data */}
<button onClick={() => navigate('/', {data: {title: 'test'}})}>Go Root with title data</button>
</>
)
};
// history !stop using in V6! -> useNavigate
import ( useHistory ) from 'react-router-dom';
const FunctionalComponent = () => {
const history = useHistory();
return (
<>
<button onClick={history.push('/')}>Go Root</button>
<button onClick={history.goBack()}>Go Back</button>
<button onClick={history.goForward()}>Go Forward</button>
<button onClick={history.go(-2)}>Go Back 2</button>
</>
)
};
// location; you can check current path or query params
import { useLocation } from 'react-router-dom';
const { pathname, search } = useLocation();
const queryParams = new URLSearchParams(search);
const FunctionalComponent = () => {
return (
<>
{/* assuming we are on /blog?sort=inverted */}
<p>Pathname: {pathname}</p>
{pathname === 'blog' && <p>You are on blog page</p>} {/* conditional based on path */}
<p>Query params: {queryParams.get('sort')}</p>
</>
)
};
// params from the navigation
import ( useParams ) from 'react-router-dom';
const { blogPost } = useParams(); // assuming we are in a <Route>: /blog/:blogPost
const FunctionalComponent = () => {
return <p>{blogPost}</p> // /blog/test will render 'test'
};
// API CALLS
// external file with logic (./services/productService)
const baseUrl = process.env.REACT_APP_API_BASE_URL; // local url eg: http://localhost:3001/ or prod url eg: https://remybeumier.be
export async function getProducts(category) {
const response = await fetch(baseUrl + 'products?category=' + category);
if (response.ok) return response.json();
throw response;
}
// app file
import React, { useState, useEffect } from 'react';
import { getProducts } from './services/productService';
export default function App() {
const [products, setProducts] = useState([]);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
// with promises
useEffect(() => {
getProducts('shoes')
.then((response) => setProducts(response))
.catch((e) => setError(e))
.finally(() => setLoading(false));
}, []);
// with async/await
useEffect(() => {
async function init() {
try {
const response = await getProducts('shoes');
setProducts(response);
} catch (e) {
setError(e);
} finally {
setLoading(false);
}
}
init();
}, []);
return (
<section>
{products.map((p) => (
<p>{p.name}</p>
))}
</section>
)
}
// API CALL WITH CUSTOM HOOK
// external custom hook
import { useState, useEffect } from 'react';
// local url eg: http://localhost:3001/ or prod url eg: https://remybeumier.be
const baseUrl = process.env.REACT_APP_API_BASE_URL;
export default function useFetch(url) {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function init() {
try {
const response = await fetch(baseUrl + url);
if (response.ok) {
const json = await response.json();
setData(json);
} else {
throw response;
}
} catch (e) {
setError(e);
} finally {
setLoading(false);
}
}
init();
}, [url]);
return { data, error, loading };
}
// app file
import React, { useState } from 'react';
import useFetch from './services/useFetch';
export default function App() {
const { data: products, loading, error, } = useFetch('products?category=shoes');
if (loading) return <p>Loading...</p>
if (error) return <p>Error: {error.message}</p>
return (
<section>
{products.map((p) => (
<p>{p.name}</p>
))}
</section>
)
}
// API call with aborting fetch request
function useDataFetcher(url) {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
const abortController = new AbortController();
setIsLoading(true);
try {
const response = await fetch(url, { signal: abortController.signal });
if (response.ok) {
const result = await response.json();
setData(result);
} else {
throw new Error('Failed to fetch data');
}
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
};
fetchData();
}, [url]);
return { data, isLoading, error };
}
// STYLE inline
import React from 'react';
const StyleComponent = () => {
return (
<h1 style={{color: 'red', fontSize: '72px'}}>Styled Title</h1>
);
};
export default StyleComponent;
// STYLE inline with a const
import React from 'react';
const styles = {color: 'red', fontSize: '72px'}
const StyleComponent = () => {
return (
<h1 style={styles}>Styled Title</h1>
);
};
// EMOTION
import React from 'react';
import styled from '@emotion/styled';
const Box = styled.div`
background-color: #ddd;
color: #444;
padding: 10px;
`;
const BoxComponent = () => {
return (
<div>
<h1>Box component</h1>
<Box>I'm a box!</Box>
</div>
);
};
export default BoxComponent;
// EMOTION EXTERNAL
import { forwardRef } from 'react';
import Styled from './Component.styled';
const Component = forwardRef((props, ref) => (
<Styled.Component ref={ref} {...props}>
Content of the <span>component</span>
<Styled.AsBox textColor="blue" />
<Styled.AsBox isRed />
</Styled.Component>
));
export default Component;
import styled from '@emotion/styled';
// styled system allows fast css with props -> m="10px" will return 'margin: 10px;'
import { layout, space, typography } from 'styled-system';
import { Box } from 'components';
export default {
Component: styled.p`
// a theme.js is adviced for consistency
${(p) => `
font-size: ${p.theme.fontSizes[2]};
text-align: center;
margin: ${p.theme.space[4]}px 0;
span {
color: ${p.theme.colors.red};
}
`}
${layout}
${space}
${typography}
`,
AsBox: styled(Box)`
// AsBox will take all CSS from Box component + those defined here
background: black;
// will apply the value passed to textColor prop
color: ${(p) => p.textColor};
// these styles will apply only if component has 'isRed' prop
${(p) =>
p.isRed &&
`
background: red;
`}
`
}
// TRANSLATE I18N
// npm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector --save
// https://react.i18next.com/latest/using-with-hooks
// i18n.js next to index.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
debug: true,
interpolation: {
escapeValue: false,
}
});
export default i18n;
// update index.js with i18n import
import './i18n';
// add translation to App.js
import React, { Suspense } from 'react';
export default function App() {
return (
<Suspense fallback="loading">
<MyComponent />
</Suspense>
);
}
// create translation files (./public/locales/en/translation.json)
{
"text": "This text comes from translation",
"translations": "Translations",
"anything": "Anything",
"withVariable": "With a variable of: {{var}}",
"item_one": "Item",
"item_other": "Items"
}
// add translation to a component
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
function MyComponent() {
const { t, i18n } = useTranslation();
const [lang, setLang] = useState(i18n.language);
function changeLang(lng) {
setLang(lng);
i18n.changeLanguage(lng);
}
return (
<div className="App">
<h1>
i18n {lang.toUpperCase()} {t('translations')}
</h1>
<h2>{t('text')}</h2>
<p>{t('anything')}</p>
<p>{t('withVariable', { var: 40 })}</p>
<p>{t('item', { count: 1 })}</p>
<p>{t('item', { count: 2 })}</p>
<button onClick={() => changeLang('en')}>EN</button>
<button onClick={() => changeLang('fr')}>FR</button>
</div>
);
}
// DEBUGGING
// add debugger anywhere to add a breakpoint
debugger;
// TESTING WITH JEST
// in package.json -> "scripts": {"test": "jest --watchAll"}
// run it with yarn test / npm run test
// TESTING WITH REACT TESTING LIBRARY
// https://github.com/testing-library/react-testing-library
// npm install --save-dev @testing-library/react
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import App from './App';
describe('Group tests in describe', () => {
test('Give useful names to your tests', () => {
render(<App />); // render your component to be tested
render(<App neededFunc={jest.fn()} />); // fake empty function to avoid errors when a function prop is required
// queries by priority: (more: https://testing-library.com/docs/dom-testing-library/cheatsheet/#queries)
const el = screen.getByRole('button', {name: '<button>'});
const el = screen.getByRole('link', {name: '<a>'});
const el = screen.getByRole('img', {name: '<img>'});
const el = screen.getByRole('heading', {name: '<h1>'});
const el = screen.getByRole('list', {name: '<ul><ol>'});
const el = screen.getByRole('listitem', {name: '<li>'});
const el = screen.getByRole('textbox', {name: '<input type="text">'});
const el = screen.getByRole('checkbox', {name: '<input type="checkbox">'});
const el = screen.getByRole('radio', {name: '<input type="radio">'});
const el = screen.getByRole('spinbutton', {name: '<input type="number">'});
const el = screen.getByRole('combobox', {name: '<select>'});
const el = screen.getByRole('option', {name: '<option>'});
const el = screen.getByRole('banner', {name: '<header>'});
const el = screen.getByRole('contentinfo', {name: '<footer>'});
// find roles with https://testing-library.com/docs/dom-testing-library/api-debugging/#logroles
const el = screen.getByLabelText('Testing react');
const el = screen.getByPlaceholderText('Testing react');
const el = screen.getByText('Testing react');
const el = screen.getByText('Testing', { exact: false });
const el = screen.getByDisplayValue('Testing react');
const el = screen.getByAltText('Testing react');
const el = screen.getByTitle('Testing react');
const el = screen.getByTestId('Testing react');
// use get when you expect element to be in DOM
const el = screen.getByRole('button');
const els = screen.getAllByRole('button');
// use query when you don't expect element to be in DOM
const el = screen.queryByRole('button');
const els = screen.queryAllByRole('button');