Why setState doesn't change local state? [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 2 years ago.
Hello guys, so I found interesting task about React, and I a little bit don't understand how to solve it
Task: Why this code is not working? Solve this.
Code:
class Test extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 1
}
}
handler() {
this.setState({count: this.state.count++})
}
render() {
console.log('render')
return (
<div>
<button onClick={this.handler}>Add 1</button>
<p>{this.state.count}</p>
</div>
);
}
}
ReactDOM.render(
<Test />,
document.getElementById("test"));
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="test"></div>
</body>
</html>

You sent wrong function reference.
It should be like this.
<button onClick={this.handler.bind(this)}>Add 1</button>
or
<button onClick={() => this.handler()}>Add 1</button>

Related

Why is my .parentNode returning undefined? [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I´m trying to make a simple To-do List, and I want it to have a button to add the tasks that I want and another button to remove all tasks but when I click the delete button I get an error: "Cannot read property 'removeChild' of undefined" I don´t know why it says the parentNode is undefined.
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>To do List</title>
</head>
<body>
<header>
<h1>To-do List</h1>
<div id="form">
<input type="text" name="" id="tarefa" value="Add an item!">
<button id="submit">Submit</button>
<button id="delete">Clear List</button>
</div>
</header>
<main>
<ul id="lista">
<li id="112">Test1</li>
<li>Test2</li>
</ul>
</main>
<script src="javascript.js"></script>
</body>
</html>
//Javascript file
const tarefa = document.getElementById("tarefa")
const adicionar = document.getElementById("submit")
const limpar = document.getElementById("delete")
const padre = document.getElementById("lista")
const fpp = document.querySelectorAll("li")
//Add the tasks
function enviar(e){
var coisa = document.createElement("li")
let escrito = tarefa.value;
padre.appendChild(coisa)
coisa.innerHTML = escrito
}
//Delete the tasks
function apagar(e){
fpp.parentNode.removeChild(fpp)
console.log("aaaa")
}
adicionar.addEventListener("click",enviar)
limpar.addEventListener("click",apagar)
.querySelectorAll returns a NodeList (because you're selecting all li tags, not just one), so you need to do a forEach loop. Give the context, I asume fds is supposed to be fpp (you never define fds in the code you provided), so here is the code you would need, given that assumption:
function apagar(e){
fpp.forEach(function(el) {
el.parentNode.removeChild(el)
})
}
Update
Use this so that you dont get null errors once the list is deleted the first time.
function apagar(e){
document.querySelectorAll("li").forEach(function(el) {
el.parentNode.removeChild(el)
})
}
How about
function apagar(){
padre.innerHTML = "";
}

How do I update the input value using an onchange event and get the value in vanilla Javascript?

I am doing an assignment where I make a simple API call using fetch to retrieve an image a of dog by breed. The one issue I can't resolve is that the input value never changes when I try to retrieve an image of a different breed. the default value, which is 'hound', reappears after I press submit. I know I need to attach an onchange event to my input but I am not sure how to write it or how to get the value after the onchange event is triggered. Any help would be greatly appreciated. I originally wrote this with jQuery but decided to rewrite it in vanilla Javascript so that's why there is no jQuery.
I put a '<---' on the line I am struggling with.
P.S I know my code isn't very good, I am new to this.
Javascript
function getJson(breed) {
fetch("https://dog.ceo/api/breed/" + breed + "/images/random")
.then((response) => response.json())
.then((responseJson) => displayResults(responseJson));
}
function displayResults(responseJson) {
const dogImage = responseJson.message;
let breedImage = "";
let container = document.createElement("div");
console.log(dogImage);
breedImage += `<img src="${dogImage}">`;
container.innerHTML = breedImage;
document.querySelector(".results-img").innerHTML = "";
document.querySelector(".results-img").appendChild(container);
}
function submitButton() {
let breedName = document.querySelector("#numberValue").value;
breedName.addEventListener().onchange.value; <---
document.getElementById("dog-input").addEventListener("submit", (e) => {
e.preventDefault();
getJson(breedName);
});
}
submitButton();
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dog Api</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form>
<input id="numberValue" type="text" value="hound" />
<button type="submit" class="submit-button">Submit</button>
</form>
<section class="results">
<h2>Look at these Dogs!</h2>
<div class="results-img"></div>
</section>
</div>
<script src="main.js"></script>
</body>
</html>
You don't need an onchange event handler. Currently you're storing the value of the input in breedName when you call submitButton. That means that breedName will never change because it is merely a reference to the value at that moment.
Instead create a reference to the element and read the value property in the submit event handler. That will get the value how it is at the time you submit.
function getJson(breedName) {
console.log(breedName);
}
function submitButton() {
const form = document.querySelector('#dog-form');
const input = document.querySelector('#numberValue');
form.addEventListener('submit', event => {
event.preventDefault();
const breedName = input.value;
getJson(breedName);
});
}
submitButton()
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dog Api</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form id="dog-form">
<input id="numberValue" type="text" value="hound" />
<button type="submit" class="submit-button">Submit</button>
</form>
<section class="results">
<h2>Look at these Dogs!</h2>
<div class="results-img"></div>
</section>
</div>
<script src="main.js"></script>
</body>
</html>

ReactDOM.render rendering page

New to ReactJS,
Can not find out why this page is not showing anything -
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="react.16.8.6.development.js"></script>
<script src="react-dom.16.8.6.development.js"></script>
<script src="babel.7.5.4.min.js"></script>
</head>
<body>
<div id="container"></div>
<script type="text/babel">
class MyClass extends React.Componet{
render() {
return(<h1>Hello React Componets!</h1>);
}
}
ReactDOM.render(
<h1>MyClass</h1>,
document.getElementById('container')
);
</script>
</body>
</html>
I am getting error in console -
VM43:19 Uncaught TypeError: Super expression must either be null or a function at _inherits (:19:113)
at :26:3
at :42:2
Try these code:
<script type="text/babel">
class MyClass extends React.Component{
render() {
return(<h1>Hello React Componets!</h1>);
}
}
ReactDOM.render(
<h1><MyClass/></h1>,
document.getElementById('container')
);
</script>
Your problem is here,
<h1>MyClass</h1>, //This is not a react component, this will only print `MyClass` as text on page
Just change,
ReactDOM.render(
<h1>MyClass</h1>,
document.getElementById('container')
);
to this,
ReactDOM.render(
<MyClass />,
document.getElementById('container')
);
Note: Correct the typo in your code,
class MyClass extends React.Componet should be class MyClass extends React.Component{
Demo

Passing data returned from function to polymer custom element

I'm starting with Polymer 3 and I'm facing an issue I cannot solv.
I have a custom element which will show a play card; its only property is an object with its suit and number. The element is more or less like this:
import {html, PolymerElement} from '#polymer/polymer/polymer-element.js';
class CardElement extends PolymerElement {
static get template() {
return html`
<style>
:host {
display: block;
}
</style>
`;
}
static get properties() {
return {
card: {
type: Object,
value: () => {
return {
suit: 'hearts',
figure: 'king'
}
}
},
};
}
ready() {
super.ready();
console.log(this.card.figure);
}
}
window.customElements.define('card-element', CardElement);
Next I want to check that every thing is working with and HTML file.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<title>card-element demo</title>
<script src="../node_modules/#webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
<script type="module">
import '#polymer/iron-demo-helpers/demo-pages-shared-styles';
import '#polymer/iron-demo-helpers/demo-snippet';
</script>
<script type="module" src="../card-element.js"></script>
<custom-style>
<style is="custom-style" include="demo-pages-shared-styles">
</style>
</custom-style>
</head>
<body>
<div class="vertical-section-container centered">
<h3>Basic card-element demo</h3>
<demo-snippet>
<template>
<card-element card='{"suit" "hearts", "figure" "1"}'></card-element>
</template>
</demo-snippet>
</div>
</body>
</html>
Console.log in ready method shows that data is binded but, whenever I try to pass a json data returned from a function, the console.log show "undefined".
<body>
<div class="vertical-section-container centered">
<h3>Basic card-element demo</h3>
<demo-snippet>
<template>
<card-element card="{{_getCard}}"></card-element>
</template>
</demo-snippet>
</div>
<script>
function _getCard() {
return JSON.stringify({
"suit": "clubs",
"figure":"1"
});
}
</script>
</body>
I checked loading data returned into a variable and binding the variable to the custom element but still didn't work.
How should I pass the data to the custom element?
Thanks for your answers.
Try this:
<script>
function _getCard() {
let data = {
"suit": "clubs",
"figure":"1"
};
return data;
}
</script>

React component is not rendering [duplicate]

I am tring to do react using below code but I am not getting html
element in the browser. There is no error in the console.
<!DOCTYPE html>
<html>
<head>
<title>React without npm</title>
<script src="https://unpkg.com/react#15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
</head>
<body>
<div id="test"></div>
<script type="text/babel">
var reactTest = React.createClass({
render: function(){
return(
<h1>React Without NPM</h1>
);
}
});
ReactDOM.render(<reactTest />,document.getElementById('test'));
</script>
</body>
</html>
Can someone please help on this.
If a React Class name starts with a lowercase letter then no methods inside the class get called, i.e. nothing Renders, and you don't get any error message in the Browser console,
because small letters are treated as HTML elements, its a rule that all React components must start with a upper case letter, so always use Upper Case.
Instead of reactTest use this: ReactTest it will work.
As per DOC:
User-Defined Components Must Be Capitalized.
When an element type starts with a lowercase letter, it refers to a
built-in component like <div> or <span> and results in a string 'div'
or 'span' passed to React.createElement. Types that start with a
capital letter like <Foo /> compile to React.createElement(Foo) and
correspond to a component defined or imported in your JavaScript file.
We recommend naming components with a capital letter. If you do have a
component that starts with a lowercase letter, assign it to a
capitalized variable before using it in JSX.
Check the working code:
<!DOCTYPE html>
<html>
<head>
<title>React without npm</title>
<script src="https://unpkg.com/react#15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
</head>
<body>
<div id="test"></div>
<script type="text/babel">
var ReactTest = React.createClass({
render: function(){
return(
<h1>React Without NPM</h1>
);
}
});
ReactDOM.render(<ReactTest />,document.getElementById('test'));
</script>
</body>
</html>
The following works fine, try it :
var ReactTest = React.createClass({
render: function(){
return(
<h1>React Without NPM</h1>
);
}
});
ReactDOM.render(<ReactTest />,document.getElementById('test'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="test" ></div>
const Some = ()=> <div />
<Some />
will work,
but
const some = () => <div />
<some />
won't work

Categories