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

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/>

Related

How can I do to hide my div using react with components?

I have this code for the App :
import React, {Component} from 'react';
import App1 from './App1';
class App extends Component {
render(){
return (
<>
<App1/>
<div>
<h1>Hello</h1>
</div>
</>
);
}
}
export default App;
And this code is for the App1
import React, {Component} from 'react';
class App1 extends Component {
render() {
return (
<>
<button>Hide</button>
</>
);
}
}
export default App1;
I would like when I click on the Button to hide my div which displays "Hello". But I have no idea to do this ?
Could you help me please ?
Thank you very much !
You can hide the div in the parent component i.e (App.js) by using props. So here are the steps you need to follow:
create a function named as handleHide in App component, and pass it as a prop to App1 component.
Define a state named as hide in App component and pass it as a prop in App1 component.
Inside App1 component use the hide prop to change the text of button(it's bonus).
Assign handleHide function passed as prop from App to App1 component's button element's onClick .
Here are the files:
App.js
import React, { Component } from "react";
import App1 from "./App1";
class App extends Component {
state = {
hide: false
};
handleHide = () => {
this.setState({ hide: !this.state.hide });
};
render() {
return (
<>
<App1 handleHide={this.handleHide} hide={this.state.hide} />
<div>{!this.state.hide && <h1>Hello</h1>}</div>
</>
);
}
}
export default App;
And App1.js will be:
import React, { Component } from "react";
class App1 extends Component {
render() {
return (
<>
<button onClick={this.props.handleHide}>
{this.props.hide ? "Show" : "Hide"}
</button>
</>
);
}
}
export default App1;
You can see the full working code here.
Using class component is perfectly fine. You can use functional component to use react hooks it makes your code more readable and less code.
App.js
import React, { useState } from "react";
import App1 from "./App1";
export default function App() {
const [show, setShow] = useState(true);
return (
<>
<App1 setShow={setShow} show={show} />
<div>{show && <h1>Hello</h1>}</div>
</>
);
}
App1.js
import React from "react";
export default function App1({ setShow, show }) {
return (
<>
<button onClick={() => setShow(!show)}>{show ? "Hide" : "Show"}</button>
</>
);
}
You create a state in App.js and pass those state down to App1.js, which look like this
class App extends Component {
constructor(){
super();
this.state = {
hidden: false
};
this.changeHiddenStatus = this.changeHiddenStatus.bind(this)
}
changeHiddenStatus = () => {
this.setState(state => ({
hidden: !state.hidden
}))
}
render(){
return (
<>
<App1 handleClick={this.changeHiddenStatus}/>
<div>
<h1>Hello</h1>
</div>
</>
);
}
}
And then in the App1.js you did this
class App1 extends Component {
render() {
return (
<>
<button onClick={props.handleClick}>Hide</button>
</>
);
}
}
These are some basic React stuff, so if you don't get it I suggest you should read the React doc again.

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>
)
}
}

two component can display in reactjs

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;

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;

Reactjs Add dynamic component into other component

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 ;

Categories

Resources