I've just started learning React.js and currently I'm working on simple "to do" app. I have encountered problem with onClick event on my submit button, it doesn't seem to work. I think I have got a problem with passing props to parent elements.
Here is my code:
var Application = React.createClass ({
getInitialState: function() {
return {
title: "Your to do list",
subTitle: "What do you have to do?",
tasks: [],
}
},
addTask: function(event) {
event.preventDefault();
alert("it works!");
},
removeTask: function() {
var taskList = this.state.tasks;
var currentTask = taskList.find(function(task) {
return task.key == event.target.key;
});
currentTask.remove();
event.preventDefault();
alert("it works!");
},
render: function() {
return (
<div className="app-container">
<Header title={this.state.title} />
<NewTaskForm subTitle={this.state.subTitle} onChange= {this.addTask} />
<TaskContainer tasks={this.state.tasks} />
</div>
);
}
});
function Header(props) {
return (
<div className="app-title">
<h1>{props.title}</h1>
</div>
);
}
function NewTaskForm(props) {
return (
<div className="new-task-area">
<form>
<label for="new-task">{props.subTitle}</label>
<input type="text" id="new-task" placeholder="Type in task" />
<button type="submit" onClick={function() {props.onChange;}}>Add task!</button>
</form>
</div>
);
}
NewTaskForm.propTypes = {
onChange: React.PropTypes.func.isRequired,
};
function TaskContainer(props) {
return (
<div className="new-task-container">
{props.tasks.map(function(task) {
return (
<p key={task.key}>{task.text}</p>
);
})}
</div>
);
}
ReactDOM.render(<Application />, document.getElementById("container"));
<!DOCTYPE html>
<html>
<head>
<title>React to do app!</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet">
<link rel="stylesheet" href="css/style.css" type="text/css" />
</head>
<body>
<div id="container"></div>
<script type="text/javascript" src="js/react.js"></script>
<script type="text/javascript" src="js/react-dom.js"></script>
<script type="text/javascript" src="js/babel-browser.min.js"></script>
<script type="text/babel" src="js/app.jsx"></script>
</body>
</html>
I would really appreciate any help because I've been trying to solve this for some time now.
you didn't call the function:
<button type="submit" onClick={function() {props.onChange();}}>Add task!</button>
you can also write it like this:
<button type="submit" onClick={props.onChange}>Add task!</button>
Related
I am using API for my website.My handleGetDetailsOrAddToFavorites event handler is working but handleRemoveFavorites EventHandler which has been implemented the same way is not working.But why???It gives no Error.Also console.log(e.target.value) in handleRemoveFavorites console logs Nothing.I want my handleRemoveFavorites to give out (e.target.value) so that i can fetch indivisual items Id and delete them from localstorage.
var url = 'https://www.themealdb.com/api/json/v1/1/search.php?s=';
var urlId = 'https://www.themealdb.com/api/json/v1/1/lookup.php?i='; //search by id
const mealList = document.getElementById('list-Items-container');
var input = document.getElementById('inputText');
const mealListFavorites = document.getElementById(
'list-Items-container-favorites'
);
window.onload = renderFavorites;
document.querySelector('form').addEventListener('submit', handleSubmitForm);
// .getElementById('get-details')
mealList.addEventListener('click', handleGetDetailsOrAddToFavorites);
mealListFavorites.addEventListener('click', handleRemoveFavorites);
function handleRemoveFavorites(e) {
e.preventDefault();
console.log(e.target.value);
}
function handleGetDetailsOrAddToFavorites(e) {
e.preventDefault();
console.log('clicked');
if (e.target.value == 'details') {
let mealItem = e.target.parentElement.parentElement;
fetch(
`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealItem.dataset.id}`
)
.then(function(res) {
return res.json();
})
.then((data) => {
mealRecipeModal(data.meals);
});
} else if (e.target.value == 'favour') {
let mealItem = e.target.parentElement.parentElement;
fetch(
`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealItem.dataset.id}`
)
.then(function(res) {
return res.json();
})
.then((data) => {
window.localStorage.setItem(
mealItem.dataset.id,
JSON.stringify(data.meals)
);
});
}
console.log(Object.entries(localStorage));
}
function mealRecipeModal(meal) {
console.log(meal[0]);
const destination = meal[0].strSource;
console.log(destination);
window.open(`${meal[0].strSource}`);
}
function handleSubmitForm(e) {
e.preventDefault();
let input = document.querySelector('input');
findFood(url + input.value);
input.value = '';
}
function findFood(address) {
fetch(address)
.then(function(res) {
//console.log(res);
return res.json();
})
.then((data) => {
console.log(data);
let html = '';
if (data.meals) {
data.meals.forEach((meal) => {
html += `<div class="food-card" data-id="${meal.idMeal}">
<div class="food-card-image">
<img src="${meal.strMealThumb}" alt="${meal.strMeal}" >
</div>
<div class="food-card-info">
<h3>${meal.strMeal}</h3>
</div>
<div class="food-card-features">
<button id="favorites" value="favour">Add</button>
<button id="get-details" value="details" >Details</button>
</div>
</div>`;
});
}
console.log(html);
mealList.innerHTML = html;
});
}
var html1 = '';
function findFoodFavorite(address) {
fetch(address)
.then(function(res) {
//console.log(res);
return res.json();
})
.then((data) => {
console.log(data);
if (data.meals) {
data.meals.forEach((meal) => {
html1 += `<div class="food-card" data-id="${meal.idMeal}">
<div class="food-card-image">
<img src="${meal.strMealThumb}" alt="${meal.strMeal}" >
</div>
<div class="food-card-info">
<h3>${meal.strMeal}</h3>
</div>
<div class="food-card-features">
<button id="favorites" value="defavour" >Remove</button>
<button id="get-details" value="details" >Details</button>
</div>
</div>`;
});
}
console.log(html1);
mealListFavorites.innerHTML = html1;
});
}
function renderFavorites() {
const urlArray = [];
console.log(Object.entries(localStorage));
for (var i = 0; i < localStorage.length; i++) {
console.log(Object.entries(localStorage)[i][0]);
urlArray.push(Object.entries(localStorage)[i][0]);
}
console.log(urlArray);
urlArray.forEach((id) => findFoodFavorite(urlId + id));
}
This is Index.html(homepage)
<!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="styles.css">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=M+PLUS+2:wght#200&family=Poppins:ital,wght#0,100;1,200&display=swap" rel="stylesheet">
<title>Meals App | HomePage</title>
</head>
<body>
<header>
<div class="topnav">
<a class="active" href="index.html">Home</a>
Favorites
Details
About
</div>
</header>
<div class="Heading">
<h1>The FoodAPP</h1>
</div>
<div class="form-container">
<form action="submit" method="get">
<input type="text" id="inputText" placeholder="Enter dish...">
<button id="btn" type="submit">Find</button>
</form>
</div>
<div id="list-Items-container">
<!-- <div class="food-card">
<div class="food-card-image">
<img src="http://placehold.it/120x120&text=image3" alt="food">
</div>
<div class="food-card-info">
<h3>Foood namae</h3>
</div>
</div> -->
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
This is favorites page
<!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="styles.css">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=M+PLUS+2:wght#200&family=Poppins:ital,wght#0,100;1,200&display=swap" rel="stylesheet">
<title>Meals App | Favaorites</title>
</head>
<body>
<header>
<div class="topnav">
<a class="active" href="index.html">Home</a>
Favorites
Details
About
</div>
</header>
<div id="list-Items-container-favorites">
<!-- <div class="food-card">
<div class="food-card-image">
<img src="http://placehold.it/120x120&text=image3" alt="food">
</div>
<div class="food-card-info">
<h3>Foood namae</h3>
</div>
</div> -->
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
I have separated your js file into two parts, one for home and one for favorite and put all of your code in window on load event :
index.js
var url = "https://www.themealdb.com/api/json/v1/1/search.php?s=";
function findFood(address, mealListEl) {
fetch(address)
.then(function (res) {
return res.json();
})
.then((data) => {
let html = "";
if (data.meals) {
data.meals.forEach((meal) => {
html += `<div class="food-card" data-id="${meal.idMeal}">
<div class="food-card-image">
<img src="${meal.strMealThumb}" alt="${meal.strMeal}" >
</div>
<div class="food-card-info">
<h3>${meal.strMeal}</h3>
</div>
<div class="food-card-features">
<button id="favorites" value="favour">Add</button>
<button id="get-details" value="details" >Details</button>
</div>
</div>`;
});
}
mealListEl.innerHTML = html;
});
}
function handleGetDetailsOrAddToFavorites(e) {
e.preventDefault();
if (e.target.value == "details") {
let mealItem = e.target.parentElement.parentElement;
fetch(
`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealItem.dataset.id}`
)
.then((res) => res.json())
.then((data) => {
mealRecipeModal(data.meals);
});
} else if (e.target.value == "favour") {
let mealItem = e.target.parentElement.parentElement;
fetch(
`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealItem.dataset.id}`
)
.then(function (res) {
return res.json();
})
.then((data) => {
window.localStorage.setItem(
mealItem.dataset.id,
JSON.stringify(data.meals)
);
});
}
}
function mealRecipeModal(meal) {
const destination = meal[0].strSource;
window.open(`${destination}`);
}
window.onload = function () {
const mealListEl = document.getElementById("list-Items-container");
function handleSubmitForm(e) {
e.preventDefault();
let input = document.querySelector("input");
findFood(url + input.value, mealListEl);
input.value = "";
}
document.querySelector("form").addEventListener("submit", handleSubmitForm);
mealList.addEventListener("click", handleGetDetailsOrAddToFavorites);
};
favorite.js:
var urlId = "https://www.themealdb.com/api/json/v1/1/lookup.php?i="; //search by id
function handleRemoveFavorites(e) {
e.preventDefault();
console.log(e.target.value);
}
function findFoodFavorite(address, mealListFavoritesEl) {
var html1 = "";
fetch(address)
.then((res) => res.json())
.then((data) => {
if (data.meals) {
data.meals.forEach((meal) => {
html1 += `<div class="food-card" data-id="${meal.idMeal}">
<div class="food-card-image">
<img src="${meal.strMealThumb}" alt="${meal.strMeal}" >
</div>
<div class="food-card-info">
<h3>${meal.strMeal}</h3>
</div>
<div class="food-card-features">
<button id="favorites" value="defavour" >Remove</button>
<button id="get-details" value="details" >Details</button>
</div>
</div>`;
});
}
mealListFavoritesEl.innerHTML += html1;
});
}
window.onload = function () {
const mealListFavoritesEl = document.getElementById(
"list-Items-container-favorites"
);
function renderFavorites() {
const urlArray = [];
for (var i = 0; i < localStorage.length; i++) {
urlArray.push(Object.entries(localStorage)[i][0]);
}
urlArray.forEach((id) => findFoodFavorite(urlId + id, mealListFavoritesEl));
}
mealListFavoritesEl.addEventListener("click", handleRemoveFavorites);
renderFavorites();
};
home.html:
</head>
<body>
<header>
<div class="topnav">
<a class="active" href="home.html">Home</a>
Favorites
Details
About
</div>
</header>
<div class="Heading">
<h1>The FoodAPP</h1>
</div>
<div class="form-container">
<form action="submit" method="get">
<input type="text" id="inputText" placeholder="Enter dish...">
<button id="btn" type="submit">Find</button>
</form>
</div>
<div id="list-Items-container">
</div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
favorite.html:
<!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="styles.css" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=M+PLUS+2:wght#200&family=Poppins:ital,wght#0,100;1,200&display=swap"
rel="stylesheet"
/>
<title>Meals App | Favaorites</title>
</head>
<body>
<header>
<div class="topnav">
<a class="active" href="home.html">Home</a>
Favorites
Details
About
</div>
</header>
<div id="list-Items-container-favorites">
</div>
<script type="text/javascript" src="favorite.js"></script>
</body>
</html>
Despite putting the document.querySelector in a window.addEventListener("load"), my document.querySelector on the "sign-in-box" returns null. Here is my HTML:
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Accueil</title>
<script src="dist/index.js"></script>
<link rel="stylesheet" href="css/global.css">
<link rel="icon" href="img/favicon.png" type="image/png" />
</head>
<body>
<div class="sign-in-box">
<form action="" method="post" autocomplete="off">
<div class="sign-in-input-group">
<div id="api-message"></div>
<h1>Chadbox™</h1>
<input type="text" name="username" placeholder="Nom d'usager" required
id="usernameBox">
<input type="password" name="password" placeholder="Mot de passe" required
id="passwordBox">
<button id="connectButton">Connexion</button>
S'enregistrer
</div>
</form>
</div>
<div id="container"></div>
<div id="startButton">Start</div>
</body>
</html>
and here is the relevant part of my Javascript:
window.addEventListener("load", () => {
document.querySelector("form").onsubmit = function () {
return signin(this);
}
new Vue({
el: '#container',
components: { carSelector },
template: '<carSelector/>'
})
let startBtn = document.querySelector("#startButton");
startBtn.addEventListener('mouseover', () =>{
startBtn.style.backgroundImage = "url('img/checkered_flag.gif')";
startBtn.style.border = "4px solid red";
})
startBtn.addEventListener('mouseleave', () =>{
startBtn.style.backgroundImage = "url('img/flag.png')";
startBtn.style.border = "4px solid teal";
})
startBtn.addEventListener('click', () =>{
window.requestAnimationFrame(moveStartBox);
let audio = document.createElement('audio');
audio.src= "./sounds/menumusic.mp3";
audio.loop = true;
audio.play();
appearLoginBox();
let node = document.querySelector("#sign-in-box");
console.log(node); //<- returns null
})
I had a similar problem with getting audio to play, which I managed to make works by just creating a new element, but I can't do that in this case. Is it because I have put the querySelector in an EventListener?
document.querySelector("#sign-in-box");
targets the id of the element
so you should either update the JavaScript selector
document.querySelector("#sign-in-box");
to
document.querySelector(".sign-in-box");
or update the html to
<div class="sign-in-input-group">
to
<div id="sign-in-input-group">
I want the background of the div changed where the button is in. Now it changes all at same time and I know why, but I don't know how I can make them work on their own.
When I press the "yes" button in server1, I want the background color of server 1 to be red and when I press the button again, it has to be the original color again. I don't mind if the script is totally different, but I would like to keep the HTML.
// var white = false
// var bgcolor;
// $("button ,yes").click(function () {
// if (white = !white) {
// bgcolor = $(this).css('backgroundColor');
// $(this).css("background-color", "red");
// } else {
// $(this).css("background-color", bgcolor);
// }
// });
var green = false
function toggleStatus()
{
if (green = !green)
{
$("#maindiv .serverstatus ").each(function ()
{
$(this).css("background-color", "red");
});
}
else
{
$("#maindiv .serverstatus").each(function ()
{
$(this).css("background-color", "#639919");
});
}
};
// function updateStatus(){
// $("#maindiv .serverstatus").each(function(){
// $(this).css("background-color", "red");
// });
// }
//
// $( document ).ready(function() {
// updateStatus();
// });
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/layout.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Grafiek</title>
</head>
<body>
<h1>Server Stats</h1>
<div id="maindiv">
<div id="server1" class="serverstatus">
<h3>(servername1)</h3>
<div>
Status:
</div>
<br>
<div>
Last Checked:
</div>
<div>
Last Online:
</div>
<div>
<button onclick="toggleStatus()">yes</button>
</div>
</div>
<div id="server2" class="serverstatus">
<h3>(servername2)</h3>
<div>
Status:
</div>
<br>
<div>
Last Checked:
</div>
<div>
Last Online:
</div>
<div>
<button onclick="toggleStatus()">yes</button>
</div>
</div>
<div id="server3" class="serverstatus">
<h3>(servername3)</h3>
<div>
Status:
</div>
<br>
<div>
Last Checked:
</div>
<div>
Last Online:
</div>
<div>
<button onclick="toggleStatus()">yes</button>
</div>
</div>
</div>
</body>
</html>
I updated your code with below steps (only changed your code to become working with solution, didnt do the cleanup and refactoring):
toggleStatus function is now accepting server_name and color_name
two parameters
toggleStatus function definition updated to change
the background color for passed server_name
Steps done to change it back on clicking again (based on feedback in comment):
create three css classes with name of your colors to give background
color of same name
update toggleStatus function to toggle the css class of color_name
// var white = false
// var bgcolor;
// $("button ,yes").click(function () {
// if (white = !white) {
// bgcolor = $(this).css('backgroundColor');
// $(this).css("background-color", "red");
// } else {
// $(this).css("background-color", bgcolor);
// }
// });
var green = false
function toggleStatus(server_name,color_name)
{
//$('#'+server_name).css("background-color", color_name);
$('#'+server_name).toggleClass(color_name);
};
// function updateStatus(){
// $("#maindiv .serverstatus").each(function(){
// $(this).css("background-color", "red");
// });
// }
//
// $( document ).ready(function() {
// updateStatus();
// });
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/layout.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Grafiek</title>
<style>
.red{
background-color:red;
}
.blue{
background-color:blue;
}
.green{
background-color:green;
}
</style>
</head>
<body>
<h1>Server Stats</h1>
<div id="maindiv">
<div id="server1" class="serverstatus">
<h3>(servername1)</h3>
<div>
Status:
</div>
<br>
<div>
Last Checked:
</div>
<div>
Last Online:
</div>
<div>
<button onclick="toggleStatus('server1','red')">yes</button>
</div>
</div>
<div id="server2" class="serverstatus">
<h3>(servername2)</h3>
<div>
Status:
</div>
<br>
<div>
Last Checked:
</div>
<div>
Last Online:
</div>
<div>
<button onclick="toggleStatus('server2','green')">yes</button>
</div>
</div>
<div id="server3" class="serverstatus">
<h3>(servername3)</h3>
<div>
Status:
</div>
<br>
<div>
Last Checked:
</div>
<div>
Last Online:
</div>
<div>
<button onclick="toggleStatus('server3','blue')">yes</button>
</div>
</div>
</div>
</body>
</html>
I tried keeping things as close to original as possible. I've also removed any JQuery code so unless you need it elsewhere you can remove that reference to trim the page a bit.
I've replaced toggleStatus() with toggleStatus(this) so it passes the element (a button in this case) so it can be referenced in the function.
Since your HTML structure is laid out this way:
<div id="server1" class="serverstatus"> <!-- This would be the button's parentNode.parentNode -->
<h3>(servername1)</h3>
<div>
<button onclick="toggleStatus(this)">yes</button>
</div>
</div>
Going up the parent/child tree twice will grab the server# div. That is what is compared in the if/else statement inside the following JavaScript:
function toggleStatus(e)
{
var parentDiv = e.parentNode.parentNode;
var bgColor = parentDiv.style.backgroundColor;
if(bgColor == "green"){
parentDiv.style.backgroundColor = "red";
}
else{
parentDiv.style.backgroundColor = "green";
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/layout.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Grafiek</title>
</head>
<body>
<h1>Server Stats</h1>
<div id="maindiv">
<div id="server1" class="serverstatus">
<h3>(servername1)</h3>
<div>
Status:
</div>
<br>
<div>
Last Checked:
</div>
<div>
Last Online:
</div>
<div>
<button onclick="toggleStatus(this)">yes</button>
</div>
</div>
<div id="server2" class="serverstatus">
<h3>(servername2)</h3>
<div>
Status:
</div>
<br>
<div>
Last Checked:
</div>
<div>
Last Online:
</div>
<div>
<button onclick="toggleStatus(this)">yes</button>
</div>
</div>
<div id="server3" class="serverstatus">
<h3>(servername3)</h3>
<div>
Status:
</div>
<br>
<div>
Last Checked:
</div>
<div>
Last Online:
</div>
<div>
<button onclick="toggleStatus(this)">yes</button>
</div>
</div>
</div>
</body>
</html>
Well I am not sure if I should be doing your homework, but here is a (not optimal) solution. I would change you HTML too, but I leave that up to you.
This will set all to green and the clicked one to red. There are more elegant solutions
function toggleStatus(e) {
$("#maindiv .serverstatus").each(function ()
{
$(this).css("background-color", "#639919");
});
$(e).parent().parent().css("background-color", "#ff0000");
};
I'm trying to learn ReactJS. In this HelloWorld script
<!DOCTYPE html>
<html>
<head>
<title>React JS Hello World</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
<script type="text/jsx">
var data=[{name: "nthhtn", text: "Sample text"}];
var DataBlock = React.createClass({
render: function() {
var entry=this.props.data.map(function (entry){
return (
<h3 name={entry.name}>
{entry.text}
</h3>
);
});
return (
<div className="data" data={this.props.data}>
<h1>Sample data block</h1>
{entry}
</div>
);
}
});
React.render(
<DataBlock data={data}/>,
document.getElementById('content')
);
</script>
</body>
</html>
I don't know why when I run script in browser, the name field in data is not displayed, only the text field is
You pass the data to getInitialState() check this fiddle https://jsfiddle.net/bs65w2hs/
var data=[{name: "nthhtn", text: "Sample text"}];
var DataBlock = React.createClass({
getInitialState: function getInitialState() {
return {
reactdata: data[0]
};
},
render: function() {
var entrydata = this.state
return <div>
<ul>
<li>name: {entrydata.reactdata.name}</li>
<li>text: {entrydata.reactdata.text}</li>
</ul>
</div>
}
});
React.render(<DataBlock />, document.getElementById('container'));
This is because you are mixing things with same variable name "entry"
render: function() {
var entryBlock=this.props.data.map(function (entry){
return (
<h3 name={entry.name}>
{entry.text}
</h3>
);
});
return (
<div className="data" data={this.props.data}>
<h1>Sample data block</h1>
{entryBlock}
</div>
);
}
Change entry to entryBlock for example (see above code). If it's not that check that there is something in entry.text.
Hope it helps.
I wrote simple Backbone.js app from manual, but this does't work. Why?
It is a HTML-code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="main.css">
<script src="source/jquery.js"></script>
<script src="source/underscore.js"></script>
<script src="source/backbone.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="menu">
<ul>
<li>Start</li>
<li>Success</li>
<li>Error</li>
</ul>
</div>
<div id="start" class="block">
<div class="userplace">
<label>Enter name<input type="text" id="username"></label>
</div>
<div class="buttonplace">
<input type="button" id="button" value="Check">
</div>
</div>
<div id="error" class="block">
<p>Error - not found!</p>
</div>
<div id="success" class="block">
<p>Win!</p>
</div>
</body>
</html>
And it is a JS-code:
var Controller = Backbone.Router.extend({
routes: {
'': 'start',
'!/': 'start',
'!/error': 'error',
'!/success': 'success'
},
start: function() {
$('.block').hide();
$('#start').show();
},
error: function() {
$('.block').hide();
$('#error').show();
},
success: function() {
$('.block').hide();
$('#success').show();
},
});
var controller = new Controller();
var Start = Backbone.View.extend({
el: '#start',
events: {
'click #button': 'check'
},
check: function() {
console.log('WiN!');
if($("#username").val() == 'test') {
controller.navigate('success', true);
}
else {
controller.navigate('error', true);
}
}
});
var starter = new Start();
Backbone.history.start();
When I select point in menu, all work normal, but when I entered name into field and press button nothing happens. Event not activated. Why?
I think you're calling navigate incorrectly.
Try this:
controller.navigate('!/success', {trigger:true});
Documentation:
http://backbonejs.org/#Router-navigate