React Component not starting up on the project - reactjs

I just started working in ReactJS and I was going through a basic React tutorial.
I have created a project and added Babel, React, ReactDOM, Webpack, Express as the dependencies.
Now I have this Counter.js :
import React, {Component} from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {count: 0};
}
render() {
return (
<button onClick={() => {this.setState({ count: this.state.count + 1 });}}>
Count: {this.state.count}
</button>
);
}
}
export default Counter;
And the main.js (which is defined as the entry point of the application in webpack.config.js file):
import React from 'react';
import ReactDOM from 'react-dom';
import Counter from './Counter.js';
ReactDOM.render(<Counter/>,document.getElementById("warbox"));
The PROBLEM is that when I start up the application, the component is not rendered on the page AND also the React DevTool Chrome extension doesn't light up (if that makes any sense).
Can't seem to figure out the problem exactly. Any help is appreciated. Apologies if its too basic.
The index.html :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="warbox"></div>
<script src="bundle.js"></script>
</body>
</html>
UPDATE : Solved. I think I should update what made it work for others to see. Heres the problem I had : Apparently the bundle.js needs to be updated by running the webpack explicitly. After making the changes, I had to stop the server and run the webpack and restart the server. It WORKED!

Related

How to break out of Next/React import hell?

After using Vue and Nuxt for more than a year, I decided to learn React and Next.js and almost immediately noticed the horrible Developer Experience.
Every stylesheet and component needs to be imported so there's always bloated import hell at the start of each component.
Not to mention if you need an extra library as you can't hook into any global object like Nuxt's this.$plugin option.
Is there some package to manage these imports for Nextjs? As far as I know, everyone who uses it doesn't mind it and that's what surprises me.
This Question may come as an insult to React and it is, but I just want at least one reason to join the hype-train as to why React is more popular.
create a file in pages directory named it _doucument.js or _document.ts (for TypeScript) and import React in it like below :
(below codes are TypeScript)
import React from 'react';
import Document, {
DocumentContext,
Head,
Html,
Main,
NextScript,
} from 'next/document';
export default class CustomDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html lang="en">
<Head>
<title>Your title</title>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
and any more doesn't require that import React in any components.

ReactJS ReactDOM Render for Separate Pages

I am in the process of migrating my pages from html and jquery to using React and I am aware that React Router and Redux are methods to handle routing when building a react application, but for the time being, I was wondering how I can change my setup to be able to render different react components for different pages. At the moment, I am able to render one react component when my index page is loaded, but I thought I could add another ReactDOM.render() beneath it and target a different div id for the component on a different page, but I noticed an error, Invariant Violation: Target container is not a DOM element. Is this related to not using a react router or something else?
here is my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import ActivityFeed from './components/App/ActivityFeed/ActivityFeed';
import CreateAnnotation from './components/App/Annotation/CreateAnnotation';
ReactDOM.render(<ActivityFeed />, document.getElementById('annotation-card'));
ReactDOM.render(<CreateAnnotation />, document.getElementById('annotation-form'));
Here is <CreateAnnotation/>:
import React from 'react';
//GET /api/activity-feed and set to state
export default class CreateAnnotation extends React.Component {
constructor(props, context) {
super(props, context);
this.state = this.context.data || window.__INITIAL_STATE__ || {
notifications: [],
reportLinks: [],
files: []
}
}
render() {
return (
<div>
<p>test</p>
</div>
)
}
}
Here is the view file:
<!DOCTYPE html>
<head>
{{> app/app-head}}
</head>
<body>
<div id="annotation-form"></div>
{{> general/bundle-js}}
</body>
</html>
{{> general/bundle-js}}:
<script src="/bundle.js"></script>
ReactDOM renders a React element into the DOM in the supplied container
and return a reference to the component (or returns null for stateless
components). If the React element was previously rendered into
container , this will perform an update on it and only mutate the DOM
as necessary to reflect the latest React element.
Technically speaking you cant render more than one React element into the DOM with multiple ReactDOM render function as it would always replace the previous rendered DOM.
See https://reactjs.org/docs/react-dom.html
The right way to do is to create multiple components and import them into App.js file. Then, your index.js file is supposed to import App.js file
as one whole component, with ReactDOM only renders App.js as a single component.

React Create simple form [duplicate]

This question already has an answer here:
import from base component can't find variable
(1 answer)
Closed 4 years ago.
I've just started to learn React and I would like to create simple page with form. Form should contain inputs keywords and city, select list date and submit buttom.
It's structure of my project
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Application</title>
</head>
<body>
<div id="root">
<div class="form-container"></div>
</div>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import './bootstrap.min.css';
import './SearchForm.js';
SearchForm.js
const formContainer = document.querySelector('.form-container')
class SeacrhForm extends React.Component {
constructor(props) {
super(props)
this.state = {
keywords: '',
city: '',
date: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
render() {
return (
<form className='search-form' onSubmit={this.handleSubmit}>
<h1>Say Hi!</h1>
</form>
)
}
}
ReactDOM.render(<SeacrhForm />, formContainer)
And I got errors on my page in browser
What did I do wrong?
Okay You need to add the following imports to you searchform.js file
import React from 'react';
import ReactDOM from 'react-dom';
and remove this line:
const formContainer = document.querySelector('.form-container')
And don't change the index.html file ever, instead create a new component like you have created searchform.js and render it in app.js and then react will automatically render that component inside
<div id=root></div>
you may not need to manually do it.
check out the following link, It may help you to understand reactJs better.
https://reactjs.org/docs/hello-world.html
Add
import React from 'react'
import ReactDOM from 'react-dom'
to SearchForm.js
Modern JS works well with ES modules, that means that you need to import dependencies into every file(module), otherwise such libraries will not be available.

React.js iframe src

index.js
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
return (
<div>
<h1>Outside iFrame</h1>
<iframe title="myiframe" src="./target.html" width="600px" height="400px"></iframe>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
index.html
<div id="root"></div>
target.html
<html>
<head></head>
<body>
<h1>Inside IFrame</h1>
</body>
</html>
the Problem is like this:
enter image description here
what's wrong with the code?
You are getting this issue because the relative url src="./target.html" is incorrect. To make sure you are using the correct url, please individually check the url generated for index.html and target.html. Also make sure that you are not making a typo error.
I tried running your code and it works fine if your target.html and index.html urls are as follows :
I can also recreate your issue, if I make a typo error in my code like so src="./typoerror.html" ,

What do I misunderstand about import in ES6?

I've done very simple markdown previewer using mark library in React. At first I did it by adding scripts to my Index.html in the
<body>
<div id="root"></div>
<script src="https://unpkg.com/react#latest/dist/react.js">
<script src="https://unpkg.com/react-dom#latest/dist/react-dom.js">
<script src="https://npmcdn.com/babel-core#5.8.38/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js"></script>
<script type="text/babel" src="script.js" ></script>
</body>
Everything worked fine, but when I removed strings react.js and react-dom.js, and added them to the script.js as below, I saw an error in console:
import React from "react.min"
import ReactDOM from "react-dom.min"
class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
_text: "",
};
}
handleChange(e) {
this.setState({
_text: marked(e.target.value)
});
}
createMarkup() {
let outPutVal = this.state._text ? this.state._text : this.state._init;
return {
__html: outPutVal
};
}
render() {
return (<form className="headDiv">
<textarea onChange={this.handleChange.bind(this)}
placeholder="Remember, be nice!"
id="inputText" rows="25" cols="100">{this.state._text}</textarea>
<output id="outputText" dangerouslySetInnerHTML={this.createMarkup()} />
</form>);
}
}
ReactDOM.render(<Input/>, document.getElementById("root"));
When using JS modules, Babel only handles the translation of import statements into CommonJS require calls - you still need a module loader of some kind to actually handle linking them all up.
Some examples of tools you could use for this are:
Webpack
Browserify
SystemJS
JSPM
That said, since you have the libraries included as script tags in your page, just removing the imports entirely would probably fix your issue - that approach really doesn't scale well though, so I encourage you to look into the above tools!
After installing with npm, you'd normally just import as follows (no .min):
import React from 'react';
import ReactDOM from 'react-dom';
You might want to consider a boilerplate like create-react-app - brilliant for getting started with an environment to focus on learning react.
create-react-app
In order to use import within your JSX code you need to use either webpack or browserify . Also you need to install these modules using npm before importing them
In order to install them run
npm install -S react-dom
npm install -S react
You can later import them as
import React from 'react';
import ReactDOM from 'react-dom';
Here is an easy tutorial that you can follow to set up your react code with webpack

Resources