Reactjs Add dynamic component into other component - javascript

I am trying to develop a webapp using reactjs and i have a issue. After more than 1 day of research, i don't understand how to do.
I want to use a component which are the main layout of my page adding other component to display in it.
In the component Base2, the child props contains another component.
import React from 'react';
import PropTypes from 'prop-types';
import { Link, NavLink } from 'react-router-dom';
const Base2 = (child) => (
<div>
<div className="top-bar">
<div className="top-bar-left">
<NavLink to="/">React App</NavLink>
</div>
<div className="top-bar-right">
<Link to="/login">Log in</Link>
</div>
</div>
<child/> // HERE the dynamic component
</div>
);
export default Base2;
The function calling it is :
const TestBase = ({props}) => {
return (<Base child={MyComponent}/>)
};
Moreover MyComponent can be a class declare following 2 methods:
import React from 'react';
import LoginForm from '../components/LoginForm.jsx';
class MyComponent extends React.Component{
constructor(props) {
super(props);
...
}
render() {
return (
<LoginForm
onSubmit={this.processForm}
onChange={this.changeUser}
errors={this.state.errors}
user={this.state.user}
/>
);
}
}
export default LoginPage;
Second method :
import React from 'react';
import { Card, CardTitle } from 'material-ui/Card';
const MyComponent = {
render() {
return (<Card className="container">
<CardTitle title="React Application" subtitle="Home page." />
</Card>);
}
};
export default MyComponent ;
During my tests, only the second method works. The lack of "instance" (something like that i guess) from the second method might be the issue?
How can I develop Base2 component to take these 2 types of component declaration?
Thanks in advance for your help

First pass the component like this:
<Base child={<MyComponent/>}/>
Then render it inside Base2 component by props.child, the way you wrote the Base2 component, child (just the argument name) will have the value of props not directly the component you are passing in props.
Write it like this:
const Base2 = (props) => (
<div>
<div className="top-bar">
<div className="top-bar-left">
<NavLink to="/">React App</NavLink>
</div>
<div className="top-bar-right">
<Link to="/login">Log in</Link>
</div>
</div>
{props.child} //here
</div>
);

In the second method seems to be a simple json containing a render method. To create component in your second method which seems to be wrote in es5 you have to use react.createClass({ render ... })
Seek on internet you will find a lot of es5 example

With the help of #Mayank Shukla i found the best way to do.
import React from 'react';
import PropTypes from 'prop-types';
import { Link, NavLink } from 'react-router-dom';
const Base2 = (props) => (
<div>
<div className="top-bar">
<div className="top-bar-left">
<NavLink to="/">React App</NavLink>
</div>
<div className="top-bar-right">
<Link to="/login">Log in</Link>
</div>
</div>
{props.child}
</div>
);
export default Base2;
The function calling it is :
const TestBase = (props) => {
return (<Base2 child={<MyComponent/>}/>)
};
First Method:
import React from 'react';
import LoginForm from '../components/LoginForm.jsx';
class MyComponent extends React.Component{
constructor(props) {
super(props);
...
}
render() {
return (
<LoginForm
onSubmit={this.processForm}
onChange={this.changeUser}
errors={this.state.errors}
user={this.state.user}
/>
);
}
}
export default LoginPage;
Second method :
import React from 'react';
import { Card, CardTitle } from 'material-ui/Card';
const MyComponent = (props) =>{
return (<Card className="container">
<CardTitle title="React Application" subtitle="Home page." />
</Card>);
};
export default MyComponent ;

Related

React js Calling Component inside component

I am learning react js.
I am unable to call countrypicker component inside cards component in app.js.
Can someone please help me?
This is my cards.js
import React from 'react';
import './Cards.css';
const Cards = () => {
return(
<div class="Cards">
<p>Cards</p>
</div>
);
}
export default Cards;
this is my countrypicker.js
import React from 'react';
import './CountryPicker.css';
const CountryPicker = () => {
return(
<div class='CountryPicker'>
<p>CountryPicker</p>
</div>
);
}
export default CountryPicker;
I am calling both components from App.js
import React,{ Component } from 'react';
import Cards from './components/Cards/Cards';
import Chart from './components/Chart/Chart';
import CountryPicker from './components/CountryPicker/CountryPicker';
import './App.css';
class App extends Component {
render(){
return (
<div className='App'>
<p className='p1' style={{color:'White'}}><b><u>Covid-19 tracker app</u></b></p>
<div>
<Cards>
<div><CountryPicker title="India"/></div>
</Cards>
</div>
</div>
);
}
}
export default App;
You need to pass children as a props to Cards, like this:
const Cards = ({ children }) => {
return(
<div class="Cards">
<p>Cards</p>
{children}
</div>
);
}

'UserInput' is defined but never used no-unused-vars 'UserOutput' is defined but never used no-unused-vars

newbie to react, following a series of lecture
i just trying to excute this simple code but something went wrong and gave me error like 'UserInput' is defined but never used* although path and src sets perfectly ok *
App.js
import React, { Component } from 'react';
import './App.css';
import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';
class App extends Component() {
render() {
return (
<div className="App">
<p>some random text</p>
<userInput />
<userOutput />
</div>
);
}
}
export default App;
UserInput.js
import React from 'react';
const userInput = () => {
return <input type="text" />;
};
export default userInput;
UserOutput.js
import React from 'react';
const userOutput = () => {
return(<div>
<button>hello </button>
</div>)
};
export default userOutput;
Improvement
Define class App extends Component{} not class App extends Component(){}
Define imported UserInput,UserInput like
<UserInput />
<UserOutput />
App.js
import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';
class App extends Component{
render() {
return (
<div className="App">
<p>some random text</p>
<UserInput />
<UserOutput />
</div>
);
}}
export default App;
Live demo for your code demo

How do I change the innerHTML of an element using React?

I want to change innerHTML of a div, when I click on the button. I don't know why, but instead of getting an error, or getting the expected result it deletes to content and replacing it with "[object Object]".
How can I get it work?
import React from 'react';
import Login from './components/login.js';
import SignIn from './components/signin';
import './App.css';
function App() {
function LoginOnClick(){
document.getElementById("wrapper").innerHTML = <SignIn />;
}
return (
<div className="container" id="wrapper">
<button onClick={LoginOnClick}>Login</button>
<Login />
</div>
);
}
export default App;
You can make use of Hooks (Added n React 16.8).
import React, {useState} from 'react';
import Login from './components/login.js';
import SignIn from './components/signin';
import './App.css';
function App() {
const [signIn, setSignIn] = useState(false);
return (
<div className="container" id="wrapper">
{signIn ? <SignIn /> : <> //This is React Fragments syntax
<button onClick={() => setSignIn(true)}>Login</button>
<Login />
</>
}
</div>
);
}
export default App;
With react you don’t have to set the innerHtml to do this, instead the more typical way is to have internal state in your component and conditionally render your SignIn component based off that. To use state the component either needs to be class or use hooks, classes are more traditional so I changed the component to be a class.
To make a class a react component you need to extend the class with the React.Component, this is because react components have lots of internal behaviours that you need to include with your class for it to be considered a component.
So
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
signIn: false,
};
this.LoginOnClick = () => {
this.setState({ signIn: true });
};
}
render() {
if (this.state.signIn) {
return (
<div className="container">
<SignIn />
</div>
);
}
return (
<div className=“container”>
<button onClick={this.LoginOnClick}>Login</button>
<Login />
</div>
);
}
}
Here is a simple way to do it:
import {useState} from "react";
const App = () => {
const [txt, setTxt] = useState("");
setTxt(<p> 'Lorem ipsum dummy text blabla.' </p>);
return(
<div>
{txt}
</div>
)
}
export default App;

Passing state value from component to component?

I've seen many answer on this website and in official docs and many other places. But I couldn't able to achieve results. That's why I'm posting this question.
SO, my question is I have 3 files named:
App.js, SignUp.js and Welcome.js.
My task is to get value in form from SignUp.js page and print that value to the Welcome.js component. I read about lifting state up and higher order components but couldn't able to do it.
Any help is appreciated.
Here's my code:
App.js:
import React,{Component} from "react";
import {BrowserRouter as Router, Link, Switch, Route} from "react-router-dom";
import SignUp from './SignUp';
import Welcome from './Welcome';
class App extends Component {
render(){
var homeMessage = () =>{
return(<div><SignUp /></div>);
}
return(
<Router>
<div>
<Route exact path="/src/Welcome" component={Welcome}/>
<Route exact path="/" component={homeMessage}/>
</div>
</Router>
);
}
}
export default App;
SignUp.js;
import React,{Component} from "react";
import {Link} from "react-router-dom";
export default class SignUp extends Component {
constructor(props){
super(props);
this.state = {
firstName:''
};
}
inputData = event =>
{
this.setState({
[event.target.name]:event.target.value
});
}
submitData = event =>
{
event.preventDefault();
}
render(){
return(
<div>
<form onSubmit={this.submitData}>
<input type="text" name="firstName" onChange={this.inputData}/>
<button type="submit"> Submit</button>
</form>
<Link to="/src/Welcome">Welcome</Link>
</div>
);
}
}
Welcome.js:
import React,{Component} from "react";
import SignUp from './SignUp';
export default class Welcome extends Component {
render(){
return(
<div>
{this.state.firstName}
</div>
);
}
}
"And please give answer if possible then in react-way only not redux or any other library. Because as per Dan Abramov article "Thinking in React" so first I want to try all scope which is available in react only."
Pass the data back to the parent from SignUp component and then pass it as a prop to the Welcome component. The other way is to store the SignUp component state in the App component so that you don't need to pass it back up when you submit.
App.js
import React,{Component} from "react";
import {BrowserRouter as Router, Link, Switch, Route} from "react-router-dom";
import SignUp from './SignUp';
import Welcome from './Welcome';
class App extends Component {
state = {
firstName: ''
}
onSignIn = (value) => {
this.setState({firstName: value});
}
render(){
return(
<Router>
<div>
<Route exact path="/src/Welcome" render={(props) => <Welcome firstName={this.state.firstName} {...props}/>}/>
<Route exact path="/" render={(props) =>{
return(<div><SignUp onSignIn={this.onSignIn} {...props} /></div>);
}}/>
</div>
</Router>
);
}
}
export default App;
SignUp.js
export default class SignUp extends Component {
constructor(props){
super(props);
this.state = {
firstName:''
};
}
inputData = event =>
{
this.setState({
[event.target.name]:event.target.value
});
}
submitData = event =>
{
event.preventDefault();
this.props.onSignIn(this.state.firstName);
}
render(){
return(
<div>
<form onSubmit={this.submitData}>
<input type="text" name="firstName" onChange={this.inputData}/>
<button type="submit"> Submit</button>
</form>
<Link to="/src/Welcome">Welcome</Link>
</div>
);
}
}
Welcome.js
import React,{Component} from "react";
import SignUp from './SignUp';
export default class Welcome extends Component {
render(){
return(
<div>
{this.props.firstName}
</div>
);
}
}
Some useful links:
How to pass data from child component to its parent in ReactJS?
Passing custom props to router component in react-router v4
ReactJS - Lifting state up vs keeping a local state

Import'd React.Component not rendering with Typescript

In App.tsx I'm importing CounterComponent.tsx , the import works if CounterComponent is exporting a function but not a React class.
Here is the commit if you want to clone/reproduce: https://github.com/Falieson/react15-meteor1.5/commit/d06ebc80c4b75850338c9a2cf11cf3ec49cafa40
Thank you for your help
App.tsx
import * as React from 'react';
import Counter from './counter/CounterComponent'
const App = (
<div className='app-container'>
{Counter}
</div>
)
export default App
CounterComponent.tsx
import * as React from 'react'
class CounterModule extends React.Component<{}, {}> {
public render() {
return (
<div>
Counter Module Placeholder
</div>
)
}
}
export default CounterModule
In React you should use <Element /> when you want to render some element. So change
const App = (
<div className='app-container'>
{Counter}
</div>
)
to
const App = (
<div className='app-container'>
<Counter/>
</div>
)

Categories

Resources