Check if props is present with ternary operator - reactjs

I have a conditional statement where I'm checking if the path includes hello and buy in them then return null. (Path is getting passed to the component as props). But if path isn't getting passed I don't want the page to break. How do I write a conditional here to check if the path is available? This is what I wrote
if path ? ((path.includes('/hello') || (path.includes('/bye')) : '') {
return null
}

Instead of checking if the path prop is undefined, you can give it a default value of an empty string and keep your code as it is.
function MyComponent({ path = '' }) {
if (path.includes('/hello') || path.includes('/bye')) {
return null;
}
// ...
}

Related

React - useParams() won't fail null / undefined check

I have two routes, /Profile which shows the user their own profile.
(it doesnt need to request this because their profile is already stored in state)
Then the second /Profile/.... which shows the user other profiles.
(it does need to request this because the state does not store all other users)
To have this functionality I have tried inputting this undefined / null check but it doesn't fail when the params are empty:
const getRequest = async () => {
const user_response = null;
console.log("param",params)
console.log("param id",params.id)
if (params !== null || params !== undefined) {
console.log("params true")
if (params.id !== null || params.id !== undefined) {
console.log("id true")
}
else{
console.log("false")
}
}
else{
console.log("false")
}
The following is the console outputs when no params are passed:
> param {}
> param id undefined
> params true
> id true
The following is the console outputs when params are passed:
> param {id: '321'}
> param id 321
> params true
> id true
How can I make it work as intended?
If your user ID can't be falsy (e.g. 0 is not a valid user ID, or '' isn't), then just
const userId = params?.id || null;
without any other fuss – userId it'll be either the ID if it's truthy, or null.
the empty object still return true, so if you want to check the object is empty or not you must do something like this:
const obj = {};
const isEmpty = Object.keys(obj).length === 0;
then you can check the param object with this
It looks like when you're not passing any params, "params" is default an empty object which is bypassing your if statementes ( because it is actually different than null and undefined)
You need a more clear condition; can use lodash library which has a method _.isEmpty() to check for empty objects or as other have stated use the Object.Keys length

Should I return true to clear .map() expects a value to be returned at the end of arrow function warning?

I'm learning React and I was getting this warning:
Array.prototype.map() expects a value to be returned at the end of arrow function array-callback-return
I cleared it by adding a return true outside of the if/else if statement, i.e.:
arr.map(foo => {
if (foo.attr === 'someKey') {
return baz
} else if (foo.attr === 'someOtherKey') {
return bar
}
return true //adding this return value clears the warning
})
Would this create any problems, or is this an okay way to clear that warning? I'm learning React so I just want to make sure I'm not developing any costly bad habits.
You don't need to return true for your piece of code. You can write your callback implementation inn a different way so that your linter doesn't give you the false warning
arr.map(foo => {
if (foo) {
return baz;
}
return bar;
})
In the above code, return bar will only execute if the if condition was false otherwise your code will return early and not reach return bar
UPDATE:
If you have a if-else-if rule, you can return undefined from the map function and filter out undefined values using filter(Boolean). It is needed you map needs to return something and if none of your conditions map, there is on return value specified
arr.map(foo => {
if (foo.attr === 'someKey') {
return baz
} else if (foo.attr === 'someOtherKey') {
return bar
}
return;
}).filter(Boolean);
The warning is because you still had not specified what to return when foo.atr is neither someKey or someOtherKey. Returning true specifies what to return in this case. But it could be any valid value

Typescript/React useRef Error: (property) React.RefObject<HTMLFormElement>.current: HTMLFormElement | null Object is possibly 'null'.ts(2531)

I'm having an issue with Typescript and it's giving me the following error listed below. The part of const formRef = useRef<HTMLFormElement>(null); seems to be good, but the issue looks to be with formRef.current.checkValidity().
How can I add the Typescript typing/get rid of the error?
Error:
(property) React.RefObject<HTMLFormElement>.current: HTMLFormElement | null
Object is possibly 'null'.ts(2531)
Code:
// React Hooks: Refs
const formRef = useRef<HTMLFormElement>(null);
// Send Verification Code
const sendVerificationCode = (event: any) => {
// Event: Cancels Event (Stops HTML Default Form Submit)
event.preventDefault();
// Event: Prevents Event Bubbling To Parent Elements
event.stopPropagation();
// const reference = <HTMLFormElement>formRef.current;
console.log('WHY IS THE FORM VALID???');
console.log(formRef.current.checkValidity());
// Check Form Validity
if (formRef.current.checkValidity() === true) {
// Validate Form
setValidated(true);
// Redux: Send Verification Code Request
dispatch(sendVerificationCodeRequest(email));
}
else {
// Do Nothing (Form.Control.Feedback Will Appear)
console.log('DO NOTHING');
}
};
As the error says, the problem is that the ref could be null — and in fact, that's what you're initializing it to. That means formRef.current may be null. Which means formRef.current.checkValidity() needs a check for whether formRef.current is null.
You can use &&:
if (formRef.current && formRef.current.checkValidity()) {
// ^^^^^^^^^^^^^^^^^^^
or the new optional chaining operator:
if (formRef.current?.checkValidity()) {
// ^
Side note: There's almost¹ never any reason for === true or === false, and certainly none above. checkValidity returns a boolean, so you already have a boolean to test with the if.
// Idiomatically:
if (x) { // Is this true?
// ...
}
if (!x) { // Is this false?
// ...
}
¹ "almost" - The only time it really makes sense is if what you're testing may not be a boolean at all and you want the check to result in false if it isn't, which is a rare edge case.
You must somehow ensure formRef.current is not null, because it could be. One way is to add this in the beginning of the callback:
if(!formRef.current) return
Also you could use the optional chaining operator, although in this case if formRef.current turns out to be null, the DO NOTHING part of code will be triggered
if(formRef.current?.checkValidity() === true)

TypeError: string.trim is not a function

I am trying a basic code to trim a function. But it displays error TypeError: string.trim is not a function. Please help why is this so.
const isEmpty = (string) =>
{
if (string.trim() === '') return true;
else return false;
};
This is to check the whether a string is empty or not. I'm making a react project with firebase.
It seems as though the string variable is sometimes not a string. You could amend the function to account for this like:
const isEmpty = (string) =>
{
if(typeof string !== "string"){ // check if the string variable is some type other than string
// do something here
}
else {
return string.trim() === '';
}
};
Your code is fine. Just make sure the 'string' parameter is actually a string
Use the builtin function typeof to confirm that
console.log(typeof(string)) // should be string
The "trim is not a function" error occurs when we call the trim() method on a value that is not a string. To solve the error, convert the value to a string using the toString() method or make sure to only call the trim method on strings.

React - how to show the difference between the current and next props?

I want to show the difference between a components current and next props. For example:
componentWillReceiveProps(nextProps) {
let diff = someFunction(this.props, nextProps);
console.log(diff);
}
How is this done?
This npm package seemed to work nicely:
https://github.com/Tixit/odiff
You can do a shallow comparison with a function like the following (I'm using ES6):
function compareObjects (objectA, objectB) {
if (objectA === objectB) {
return true // return true if both variables are referencing the same object
}
let key
// check what property does objectA have that objectB has not
for (key in objectA) {
if (objectA.hasOwnProperty(key) && !objectB.hasOwnProperty(key)) {
return false // return false if there's a difference
}
}
// check what property does objectB have that objectA has not
for (key in objectB) {
if (objectB.hasOwnProperty(key) && !objectA.hasOwnProperty(key)) {
return false // return false if there's a difference
}
}
}
Note that this is only shallow checking and does the comparison on first level. It only compares if the objects given consist of the same values (therefore it's called shallow).

Resources