two component can display in reactjs - javascript

I have two component in the same work space in reactjs but just one is displaying
import React, { Component } from 'react';
import logo, { ReactComponent } from './logo.svg';
import './App.css';
import ReactDOM from "react-dom";
class App extends React.Component {
render() {
let helloWorld = 'Welcome to good programming React';
return (
<div className="App">
<h2> {helloWorld}</h2>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
class Form extends React.Component {
constructor(props) {
super(props)
this.state = { username: '' }
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event) {
this.setState({ value: event.target.value })
}
handleSubmit(event) {
alert(this.state.username)
event.preventDefault()
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.username} onChange={this.handleChange} />
<input type="submit" value="Submit" />
</form>
)
}
}
export default (App,Form)
output from browser gives just the form.how can i do to display both App and form

The problem here is that you are mounting the node <App/> but it does not contain your <Form/> component.
You just need to call <Form/> inside your <App/> component like this
class App extends React.Component {
render() {
let helloWorld = 'Welcome to good programming React';
return (
<div className="App">
<h2> {helloWorld}</h2>
<Form/>
</div>
);
}
}

Call <Form /> inside App component and then export your App component
export default App;

You might not be understanding how React works, and you might be confused with this code
ReactDOM.render(<App />, document.getElementById('root'));
What this code essentially does is renders the App Component into the element in the index.html with the id root. The reason why your second component is not rendering is because it is not experiencing a ReactDOM.render nor is it included in the App Component.
By convention, App component should be the only component experiencing ReactDOM.render, and all the other component to be rendered must be inside the App component. Just like what #sudo97 is saying

ReactDOM.render function needs to have the Root component or the parent component which is to be passed as a first parameter.
ReactDOM.render(<App />, document.getElementById('root'));
Here App is the root component, you can include <Form /> inside of the App component to render both the components.

You are not rendering the <Form /> component. Heres the simplest solution code to solve your issue:
import React from "react";
import ReactDOM from "react-dom";
import "./App.css";
class Form extends React.Component {
constructor(props) {
super(props);
this.state = { username: "" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
alert(this.state.username);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.username}
onChange={this.handleChange}
/>
<input type="submit" value="Submit" />
</form>
);
}
}
class App extends React.Component {
render() {
let helloWorld = "Welcome to good programming React";
return (
<div className="App">
<h2> {helloWorld}</h2>
<Form />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
export default App;

Related

How to change function component code to class component

I have a functional component but I need in class component. So I tried to change this but had some error but I can't find what I'm missing.
import React, { useState } from 'react';
import DateTimeRangePicker from '#wojtekmaj/react-datetimerange-picker';
function App() {
const [value, onChange] = useState([new Date(), new Date()]);
return (
<div>
<DateTimeRangePicker
onChange={onChange}
value={value}
/>
</div>
);
}
export default App
I tried this but it's not working:
import React, { Component } from 'react'
import DateTimeRangePicker from '#wojtekmaj/react-datetimerange-picker';
export default class App extends Component {
constructor(props){
super()
this.state = {
value:new Date()
}
}
render() {
return (
<div>
<DateTimeRangePicker
onChange={() => this.setState({value:new Date()})}
value={this.state.value}
/>
</div>
)
}
}
As explained in npm page, onChange function returns a value. So you could change class component like this:
import React, { Component } from 'react'
import DateTimeRangePicker from '#wojtekmaj/react-datetimerange-picker';
export default class App extends Component {
constructor(props){
super(props)
this.state = {
value:[new Date(), new Date()],
}
}
render() {
return (
<div>
<DateTimeRangePicker
onChange={(value) => this.setState({value:value})}
value={this.state.value}
/>
</div>
)
}
}

React js receiving props from child component to mother component

Let, we have a parent component like this,
import React from 'react';
export default class ParentComp extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className='padding'>
{this.props.children}
</div>
);
}
}
Okay, now i want to use this component like this
<ParentComp fillbg="#389457">
content goes here.......
</ParentComp>
What needs to be changed in parent component to apply that background (fillbg)
import React from 'react'
export default const ParentComp = ({children, fillbg}) => (
<div className='padding' style={{backgroundColor: fillbg}}>
{children}
</div>
);
Pass it as prop to your component and use it
import React from 'react';
export default class ParentComp extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className='padding' style={{backgroundColor: this.props.fillbg}}>
{this.props.children}
</div>
);
}
}
Pass the fillbg prop like this
<ParentComp fillbg="#389457">
content goes here.......
</ParentComp>

ReactJS <form> onSubmit forward to new component and page

I might be misunderstanding React, in which case I welcome suggestions to rearchitect my site.
My desired behaviour is after submitting the SimulationForm the user is then forwarded to another component called SimulationResults. This will take an id used to send a database query.
The current behaviour is that the simulation doesn't forward at all after submitting, staying on the same page.
Ideally, so that the user can easily return to the results in the future I would like it if the simulation id could be passed as a url path parameter to the results page, intead of going through the submit form again.
I have an index.js that looks like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import SimulationForm from './simulation_form'
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<SimulationForm />, document.getElementById('root'));
serviceWorker.unregister();
And simulation_form.js like this:
import React from 'react';
export default class SimulationForm extends React.Component {
constructor(props) {
super(props);
this.state = {
simulationName: "",
...
...
};
this.handleSubmit = this.handleSubmit.bind(this);
...
}
...
...
handleSubmit(event) {
event.preventDefault();
...
...
}
...
...
return(
<form id="simulationForm" className="centered" onSubmit={this.handleSubmit}>
<label>Simulation name:</label>
<input type="text" placeholder="enter name here" name="simulationName" value={this.state.simulationName} onChange={this.handleChange} />
...
...
);
}
}
At the end of the handleSubmit function I've tried:
return <SimulationResults />;
and
ReactDOM.render(<SimulationResults />, document.getElementById('root'));
to no success. It's clear I don't understand how React wants me to set this up. I've been reading the docs and the web but can't find any examples of what I want to achieve. I'm also unsure as to how I pass state (an id string) to the results component from the form component.
simualation_results.js:
import React from 'react';
export default class SimulationResults extends React.Component {
constructor(props) {
super(props);
this.state = {
simId: ""
}
}
...
...
render() {
return <form id="simulationResults" className="centered" onSubmit={this.queryDatabase}>
<input type="text" placeholder="enter simId" name="simId" value={this.state.simId} onChange={this.handleChange} />
<input type="submit" value="Submit" />
</form>
}
#i.brod pointed me in the direction of react-router to achieve what I wanted.
npm install react-router-dom
I then added a <Router> to my index.js:
import {
BrowserRouter as Router,
Switch,
Route,
useParams
} from "react-router-dom";
ReactDOM.render(<Index />, document.getElementById('root'));
export default function Index() {
return (
<Router>
<div>
<Switch>
<Route exact path="/">
<SimulationForm />
</Route>
<Route path="/results/:id?">
<Results />
</Route>
</Switch>
</div>
</Router>
);
}
Where path="/results/:id?" matches /results as well as /results/{anything}.
I made my SimulationResults component a function instead of a standalone component.
function Results() {
let { id } = useParams();
queryDatabase(id);
return (
<div className="centered" >
<h3 id="results-header">waiting...</h3>
<form id="simulationResults" onSubmit={(e) => {e.preventDefault(); queryDatabase(document.getElementById("simHash").value);}}>
<input id="simHash" type="text" placeholder="enter simHash" />
<input type="submit" value="Submit" />
</form>
</div>
)
}
SimulationForm is still a component:
export default class SimulationForm extends React.Component {
...
}
To redirect from / to /results:id at the end of the the form's onSubmit I added:
window.location.href = '/results/' + id

Variables in React

I've been working with React for the last days, so don't blame me.
But I'm trying to display my full name with a button but I get an error when I d this.
import React from 'react';
import logo from './logo.svg';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Val',
surname: 'Vree',
age: 17,
nationality: 'Netherlands'
};
}
render() {
return (
<div>
<Header header={this.state.name} />
<Content content={this.state.surname} />
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<p>I'm {this.props.content}</p>
</div>
);
}
}
export default App;
How can I put multiple variables in the Content class? Sorry for everything, because I been learning it for some days and I don't have some knowledge of React.
you can pass it in a few ways:
<Content content={ `${this.state.name} ${this.state.surname}`} />
or
<Content name={this.state.name} content={this.state.surname} />
and get
class Content extends React.Component {
render() {
return (
<div>
<p>I'm {this.props.name} {this.props.content}</p>
</div>
);
}
}
just add multiple props. if your feeling lazy want just one prop just pass this.state and you can pass the entire object. but this is bad practice generally.
hope this helps
import React from 'react';
import logo from './logo.svg';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Val',
surname: 'Vree',
age: 17,
nationality: 'Netherlands'
};
}
render() {
return (
<div>
{/* <Header header={this.state.name} /> */}
<Content
name={this.state.name} //<---- add more props
surname={this.state.surname}
age={this.state.age}
nationality={this.state.nationality}
/>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<p>I'm {this.props.name} {this.props.surname}</p>
<p> I am {this.props.age} and i'm from {this.props.nationality}</p>
</div>
);
}
}
export default App;
When you say variables I think you mean props. You can pass props from a parent component to a child component like so
<ChildComponent propOne={this.state.stateOne} propTwo={this.state.stateTwo} />
Now ChildComponent has access to both of those props passed down from the parent component.
In ChildComponent you can access propOne by doing props.propOne (or this.props.propOne if ChildComponent is a class component).
In your case, you should do
import React from 'react';
import logo from './logo.svg';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Val',
surname: 'Vree',
age: 17,
nationality: 'Netherlands'
};
}
render() {
return (
<div>
<Header header={this.state.name} />
<Content name={this.state.name} surname={this.state.surname} />
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<p>I'm {this.props.name} {this.props.surname}</p>
</div>
);
}
}
export default App;

React.js, this.props.changeTitle is not a function

I'm trying to create a title and a textbox below it using React, ES6, Webpack and Babel. The content of the title changes/re-renders as we type inside the textbox.
There are primarily two files, Header.js and app.js
//app.js
import React from "react";
import ReactDOM from "react-dom";
import Header from "./Header/Header";
export default class App extends React.Component
{
constructor()
{
super();
this.state = ({title: "Welcome"});
}
changeTitle(newtitle)
{
this.setState({title: newtitle});
}
handleChange(e)
{
const input = e.target.value;
this.props.changeTitle(input);
}
render()
{
return(
<div>
<Header changeTitle = {this.changeTitle.bind(this)} title = {this.state.title}/>
<input onChange={this.handleChange.bind(this)} />
</div>
);
}
}
const element = document.getElementById('app');
ReactDOM.render(<App/>,element);
======================================================
//Header.js
import React from "react";
import ReactDOM from "react-dom";
export default class Header extends React.Component
{
render()
{
return(
<div>
<h1>{this.props.title}</h1>
</div>
);
}
}
If I move the handleChange(e) method and <input> tag line from app.js to Header.js then it works fine, but otherwise I get error that "this.props.changeTitle is not a function", which is inside handleChange(e) method.
You don't pass a prop to <App /> called changeTitle when you render it ReactDOM.render(<App/>,element);
It looks like you just want this.changeTitle instead of this.props.changeTitle
Theres no need to pass the function changeTitle() to the <Header/> just have handleChange() call this.setState().
handleChange(e)
{
const input = e.target.value;
this.setState({title: input});
}
render()
{
return(
<div>
<Header title = {this.state.title}/>
<input onChange={this.handleChange.bind(this)} />
</div>
);
}
React will rerender <App/> which in turn will rerender() <Header/>

Categories

Resources