This question already has answers here:
Template literals like 'some ${string}' or "some ${string}" are not working
(7 answers)
Closed 5 years ago.
I'm learning React using a textbook and the string replacer ${} from this particular example doesn't work and can't figure out why. I've double checked any typos to make sure. Other examples from the book has worked fine so far.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script crossorigin src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Hello extends React.Component {
constructor (props) {
super(props)
this.clickHandler = this.clickHandler.bind(this) //isolates 'this' of Hello class from other 'this'
}
clickHandler (e) {
const name = this.props.name
window.alert('Hello, ${name}') //!!this doesn't work....
}
render () {
return (
<div onClick={this.clickHandler}>Say Hello</div>
)
}
}
ReactDOM.render((<Hello name="Johnny" />),document.getElementById("root"))
</script>
</body>
</html>
use back-tick
window.alert(`Hello, ${name}`)
Related
This question already has an answer here:
Why doesn't my arrow function return a value?
(1 answer)
Closed 9 months ago.
I've been trying to figure out why my components will not display at all for the past 5 hours. Any help is greatly appreciated.
Here is the source:
index.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">
<script src="https://unpkg.com/react#18/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js" crossorigin></script>
<script src="modules/Container.js"></script>
<script src="modules/CategoryFolder.js"></script>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script>
let root = $('#root')[0];
reactroot = ReactDOM.createRoot(root);
reactroot.render(React.createElement(Container));
</script>
</body>
</html>
modules/Container.jsx:
const SPACING = 10;
class Container extends React.Component {
constructor() {
super();
this.state = {categories: []};
}
componentDidMount() {
$.ajax({
url: './items/categories',
dataType: 'json',
async: true,
success: (categories) => {
this.setState({categories});
}
})
}
render() {
this.state.categories.map((category, i, a)=>{
<CategoryFolder style={{'z-index':i,top:i*SPACING+'%'}} CategoryTitle={category}></CategoryFolder>
})
}
}
modules/CategoryFolder.jsx:
function CategoryFolder(props) {
let css_class = '';
let id = Number.parseInt(props.key) + 1;
if (id % 3 == 0)css_class = 'tert-tag';
else if (id % 3 == 2) css_class = 'even-tag';
return (
<div class="gwd-div-7ybz" name="folder-container">
<div class={"gwd-div-qb7z " + css_class} name="folder-tag-container">
<fieldset class="gwd-fieldset-poz5" name="folder-tag-text"><h1 class='category-title'>{props.CategoryTitle}</h1></fieldset>
</div>
<svg data-gwd-shape="rectangle" class="gwd-rect-c8gx" name="folder-recipe-body"></svg>
</div>
)
}
When I debug all this, the root element is identified and I can see the ajax function succeeding and the render function of Container running. But, for whatever reason, the root element remains untouched as <div id="root"></div> without ever being modified.
Thanks in advance!
Update: I should mention that the console shows no errors at all!
Update 2: The files posted are .jsx while the ones included in index.html are transpiled with npx babel --watch modules/src --out-dir public/modules --presets react-app/prod
You don't return <CategoryFolder style={{'z-index':i,top:i*SPACING+'%'}} CategoryTitle={category}></CategoryFolder> in map() function
This question already has answers here:
Convert a React.element to a JSX string
(4 answers)
Closed 1 year ago.
How would I take HTML stored in a variable and convert it into a string?
Take this:
var html = <div>html</div>;
And Make it into this:
var html = "<div>html</div>"
As per the flagged duplicate you can use ReactDOMServer.renderToString(element), or ReactDOMServer.renderToStaticMarkup(element) to render a react element as an HTML string (renderToStaticMarkup() doesn’t render the extra DOM attributes that React uses internally, such as data-reactroot).
Both methods can be used in both the server and browser environments.
function App() {
const html = (<div>html</div>);
return (
<div>
{ReactDOMServer.renderToStaticMarkup(html)}
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script crossorigin src="https://unpkg.com/react#17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom-server.browser.production.min.js"></script>
<div id="root"></div>
You can get the element's outerHTML property:
var elem = document.querySelector('div');
var res = elem.outerHTML;
console.log(JSON.stringify(res))
<div>html</div>
I would like to access a variable and a set of functions from within a javascript segment. I have two files:
testJSP.jsp
<%#page import="test.tester"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%
String thing = "Exciting String";
tester testy = new tester(thing);
%>
<input type="submit" onclick="test()" value="Sample Text" />
<div id="testDiv" >Boring String</div>
<script language="javascript" >
funciton test() {
document.getElementById("testDiv").innerHTML = <%=testy.getString()%>;
}
</script>
</body>
</html>
tester.java
package test;
public class tester {
private String privy;
public tester(String testString) {
privy = testString;
}
public String getString() {
return "new " + privy;
}
}
Essentially, when the button is clicked, I want the element with id "testDiv" to be changed according to the function in the java file. I may be overlooking a very simple method, or perhaps there is a far more complex way of approaching this seemingly simple problem.
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
<!-- This is the HTML element -->
<h1 id="greeting"></h1>
JS
var currentUser = localStorage.getItem("currentUser");
document.getElementById("greeting").innerHTML = "Hi " + currentUser;
Here is what happens when inspect the page, it says:
Uncaught TypeError: Cannot set property 'innerHTML' of null(…)
This would be the entire code file.
//mypublicwebsites.tk/artem/databases/a/load_home.js
//This isn't the complete code because I cannot use 'localStorage' in a code snippet
//excluding unneeded code
var isSignedIn = true;
//The current user, lets just say that is me
var currentUser = "Sean";
if(isSignedIn) {
load();
} else {
window.location.replace("index.html");
}
function logOut () {
localStorage.setItem("isSignedIn","false");
localStorage.setItem("currentUser", "none");
window.location.replace("index.html");
}
function load() {
document.querySelector(".greeting").innerHTML = "Hi " + currentUser + "!";
}
<!DOCTYPE html>
<html>
<head>
<title>Artem Inc. | Database A -> Home</title>
<script src="mypublicwebsite.tk/artem/databases/a/load_home.js"></script>
</head>
<body>
<div id="menu">
<button onclick="logOut()">Log Out</button>
</div>
<h1 class="greeting"></h1>
</body>
</html>
It does seem to work in the snippet but not in the browser.
Fine, I'll post the answer I found. You need to wait for the webpage to load and then execute the script, so I put the script right before the closing body tag.
After checking your source over at Github i notice that there is no element of id greeting at https://github.com/codecademy123/codecademy123.github.io/blob/master/artem/databases/a/home.html :
<!DOCTYPE html>
<html>
<head>
<title>Artem Inc. | Database A -> Home</title>
<script src="load_home.js"></script>
</head>
<body>
<div id="menu">
<button onclick="logOut()">Log Out</button>
</div>
<h1 class="greeting"></h1>
</body>
</html>
No id but there is a class with the name greeting.
Here's an updated and simplified fiddle:
https://jsfiddle.net/tommiehansen/ndd0c7rh/2/
Basically we just use document.querySelector('.greeting') instead of document.getElementById('greeting') since the id greeting will always return undefined if it does not exist.
If you want to still use an id simply change the source code for home.html from <h1 class="greeting"></h1> to <h1 id="greeting"></h1>. The important part here is to query the DOM after what you've set the class or id to be. Because if you do not match these it will always return as undefined since your javascript will not be able to find the selector.
I've been going through a react.js tutorial, with a simple hello world example. I can't find a reason why the following shouldn't work, but I keep getting this error.
Uncaught Error: Invariant Violation: React.render(): Invalid component element.
I have the following code. It seems to work if I do React.createElement, but not for the JSX elements.
<!doctype html>
<html>
<head>
<script src="https://fb.me/react-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<script type="text/jsx">
document.body.onload = function(){
console.log("shuff")
var HelloWorld = React.createClass({
render: function(){
return <div>Hello, Ian Shuff!</div>;
}
});
React.render( new HelloWorld(), document.getElementById("test"))
}
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
You should pass to render <HelloWorld />, not new HelloWorld()
React.render(<HelloWorld />, document.getElementById("test"))
Example
jsx-in-depth
Or you can use React.createElement, like so
React.render(React.createElement(HelloWorld, null), document.getElementById("test"))
Example