This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 8 months ago.
Im getting this error and i dont know how to solve it... It says that my "count" is defined but never used. I'm using it in my template but it's like it doesnt feel it.
<template>
<div class="root">
<button v-on:click="count += 1">Thumbs up</button>
<button v-on:click="count -= 1">Thumbs down</button>
<div class="countResult">
{{count}}
</div>
</div>
</template>
<script>
export default {
data: () => {
count: 0
}
}
here's my full error: ./src/components/voteSnippets.vue
Module Error (from ./node_modules/eslint-loader/index.js):
C:\Users\x\x\x\snippets\code-snippets\src\components\voteSnippets.vue
17:9 error 'count:' is defined but never used no-unused-labels
✖ 1 problem (1 error, 0 warnings)
1 error and 0 warnings potentially fixable with the --fix option.
You have to return an object containing all your variables from the data function of yours.
Correct code would be
export default {
data: () => {
return {
count: 0
}
}
}
Related
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 1 year ago.
I use React with CSS Module and My code have many repetitive line.
So, I use function to make simple. here is my code.
const SassComponent = () => {
function stylesBox(color) { return `${styles.box} ${styles}.${color}` }
return (
<div className={styles.SassComponent}>
<div className={stylesBox('red')} />
<div className={`${styles.box} ${styles.orange}`} />
<div className={`${styles.box} ${styles.yellow}`} />
<div className={`${styles.box} ${styles.green}`} />
.....
There is my problem when i use 'color' argument with '.'operator. It doesn't work!
How can i fixed it?
Thank you for reading.
Try:
${styles[color]}
instead of
${styles}.${color}
This question already has answers here:
Usage of the backtick character (`) in JavaScript
(11 answers)
Closed 2 years ago.
I am new to JSX, and javascript in general, and I am confused by {} having multiple meanings based on what is in and around them. I am confused about the difference between {} and ${} in the following example from the React docs.
In an example explaining hooks, we see <button onClick={() => this.setState({ count: this.state.count + 1 })}>
Here, the innermost curly braces indicate that a JS object with one key: value pair is what is being passed as the sole parameter to this.setState().
Later, in the componentDidUpdate and componentDidMount methods we see document.title = `You clicked ${this.state.count} times/`;
In this snippet, the curly braces do not surround a key: value pair so I know it not a JSON object. It's inside {} in JSX so this.state.count should just evaluate to a number but what is the meaning of the $ in this expression?
Thanks in advance!
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
The `` and $ combination is a way to concatenate strings that's easier to read than the old way of using +.
For example say you have obtained the users firstname through some input you might output some string like
Hi There Mark!
where Mark is the users name.
You can do this with either
"Hi There" + user.firstname + "!"
or
`Hi There ${user.firstname}!`.
In JavaScript content between backticks is a template string and ${...} is the syntax you can use to embed a JavaScript expression inside the template.
In JSX {...} is used to assign a dynamic value (as opposed to a static one) to a prop on a component.
This question already has answers here:
Uncaught TypeError: Cannot read property 'map' of undefined at {Component}.render in ReactJs
(3 answers)
How to handle calling functions on data that may be undefined?
(2 answers)
Closed 4 years ago.
this my redux array that i get from a backend node js api
errors:
errors: Array(1)
0: {location: "body", param: "name", value: "mamadou bah transfert", msg: "ce nom est déja utilisé"}
length: 1
And in React Iam triying to show the errors like this
<div class="col m12">
{this.props.offices.errors.errors?
<span className="center-align red-text">
{this.props.offices.errors.errors.map((error,i) => <p key={i}> {error.param=='name'?error.msg:''}</p>)
</span> : '' }
</div>
this is the errors that i get always
react-errors
Since the errors comes from an asynchro request, you should secure the case that the object doesn't exist yet.
this.props.offices && this.props.offices.errors.errors.map(...)
However to be 100% sure that it won't fail, I would use a defualt value of offices and also check if the errors exists and it's an iterable array.
const { offices = {} } = this.props;
offices.errors && Array.isArray(offices.errors.errors) && offices.errors.errors.map(...);
Try with this
The point is that when you want to access nested objects, you need to first check whether the nested object really exist and then access it like using below conditional check in your case
<div class="col m12">
{this.props.offices && this.props.offices.errors && this.props.offices.errors.errors?
<span className="center-align red-text">
{this.props.offices.errors.errors.map((error,i) => <p key={"Key-"+i}> {error.param=='name'?error.msg:''}</p>)
</span> : '' }
</div>
This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 4 years ago.
Issue
Hello, Thanks ahead for anyone willing to help me, I have a problem with sorting an object array in js.
In this component I keep an array inside this.state of id, hours, day, and active.
My issue is when I try to sort the object.hours array the function won't sort by my logics and understanding of this comparator and the array stays same even if the sort expression is false.
Which can be found under sortHoursByTime declaration.
Expected Behavior
if (obj1.toTime < obj2.fromTime) then sort the array where obj1 is first in order.
Code:
export default class SetWorkingHours extends Component {
constructor() {
super();
this.state = {
workingDays: ['א׳', 'ב׳', 'ג׳', 'ד׳', 'ה׳', 'ו׳'].map((day, _id) => ({
_id,
name: day,
hours: [],
active: false,
})),
activeButton: -1,
}
}
static defaultProps = {};
sortHoursByTime(day) {
let sortedDays = day;
sortedDays.hours.sort((obj1,obj2) => obj1.fromTime < obj2.toTime);
this.setState({workingDays: sortedDays});
}
appendWorkingHours = (hours) => {
let dateHours = {
fromTime: this.formatDateToHourString(new Date(hours.fromDate)),
toTime: this.formatDateToHourString(new Date(hours.toDate))
};
let selectedWorkingDays = this.state.workingDays;
selectedWorkingDays.forEach((day) => {
if (day.active && this.isHoursValid(day, dateHours)) {
day.hours.push(dateHours);
this.sortHoursByTime(day)
}
});
this.setState({workingDays: selectedWorkingDays})
} // Editor's note: the closing curly brace of appendWorkingHours method
// was missing, so I added this line.
};
Environment
react-native -v: "0.54.2"
node -v: v9.8.0
npm -v: 5.6.0
yarn --version: 1.5.1
target platform: iOS
operating system: OSX
When using Array.sort in JavaScript with a custom sorting function you need to return -1 less then, 0 equals, 1 greater then.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
This should fix your issue.
sortHoursByTime(day){
let sortedDays = day;
// Switch from < to -
sortedDays.hours.sort((obj1,obj2) => obj1.fromTime - obj2.toTime);
this.setState({workingDays: sortedDays});
}
This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 7 years ago.
I want to be able to run a function that is passed by name from a data attribute on the HTML side. I've tried the following below.
HTML:
<div class="generic-select" data-help-on-shown="genericFunction" >
</div>
Javascript:
function genericFunction() {
console.log("generic function called");
}
Other Javascript (separate file):
//stepEl is correct divider from above
var genFunction = typeof (stepEl.data("helpOnShown")) === "undefined"
? null
: stepEl.data("helpOnShown");
//this prints "genericFunction" as expected
console.log("genFunction = " + genFunction);
if (genFunction) {
genFunction(); //gives error!
}
However, this gives me an error. Is there a way to call a function by a string name?
If the function is "global", it exists as a property of window:
window[functionname]()