I have a simple login form component that when I click, would like for the form to disappear and only display my json. I am a little rusty with working with react state, and appear to have the opposite effect of what I am trying. When I click on my button event, the json I am displaying will toggle appearing and disappearing, but the form stays static. I need the form to disappear and the page to populate with my grid.
Here is my components
index.jsx
import React from 'react';
import SignUp from '../SignUp';
import Cards from '../Articles/Cards';
export default class Gecko extends React.Component {
constructor(props) {
super(props);
this.state = { requestedPostsThatWeGotFromGecko: null, }
this.clickMe = this.clickMe.bind(this)
}
clickMe = () => {
const {requestedPostsThatWeGotFromGecko} = this.state;
this.setState({ requestedPostsThatWeGotFromGecko: !requestedPostsThatWeGotFromGecko })
}
render() {
console.log(this.state);
return (
<div className='gecko'>
<SignUp login={() => this.clickMe()}/>
{this.state.requestedPostsThatWeGotFromGecko &&
<Cards />
}
</div>
);
}
}
Sign up component
import React from 'react';
export default class SignUp extends React.Component {
render() {
const onClick = () => {
this.props.login();
console.log('rich');
}
return (
<div className='sign-up'>
<table className='sign-up-form'>
<tbody>
<div class="gecko-signup__tabs"><button id="gecko-signup" data-selected="yes">Sign Up</button><button id="gecko-login" data-selected="">Log In</button></div>
<tr>
<td>
<p id="signUpFree">Sign Up for Free</p>
</td>
</tr>
<div id="inputs-section">
<tr>
<td><input id="first" placeholder="First Name*" /></td>
<td><input id="last" placeholder="Last Name*" /></td>
</tr>
</div>
<tr>
<td colSpan="2"><input placeholder="Email Address*" /></td>
</tr>
<tr>
<td colSpan="2"><input placeholder="Set A Password*" /></td>
</tr>
<tr>
<td colSpan="2"><input id="getStarted" type="submit" value="Get Started" onClick={onClick}/></td>
</tr>
</tbody>
</table>
</div>
);
}
}
CardSetup component
import React from 'react';
import SignUp from '../SignUp';
export default class Articles extends React.Component {
constructor(props) {
super(props);
this.state = {
requestedPostsThatWeGotFromGecko: [],
}
}
componentDidMount(){
const api = 'https://5d445466d823c30014771642.mockapi.io/api/v1/products';
const request = new Request(api);
// Fetch isn't browser compatible...Might should fix.
fetch(request)
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error('Something went wrong on api server!');
};
}).then(response => {
this.setState({
requestedPostsThatWeGotFromGecko: response
});
})
.catch(error => {
console.error(error);
});
}
render() {
return(
<div className='articles'>
{this.state.requestedPostsThatWeGotFromGecko.map(product => {
return (
<div className='flex-grid'>
<div className="card">
<div className="overflow">
<img className='productImage' src={product.image}></img>
</div>
<div className='card-body'>
<p id='name'>{product.name}</p>
<p id='description'>{product.description}</p>
<p id='price'>{product.price} </p>
</div>
</div>
</div>
);
})
}
</div>
)}}
Final Cards component
import React from 'react';
import Articles from './CardSetup';
export default class Cards extends React.Component {
render() {
return(
<div className="cards">
<h2>Products</h2>
<div className="column">
<Articles />
</div>
<div className="column">
<Articles />
</div>
<div className="column">
<Articles />
</div>
<div className="column">
<Articles />
</div>
</div>
);
}
}
I am pretty sure that I am setting the state incorrectly somewhere along the line after I press the button. I am thinking about jquery and wanting to "hide" the element but I know that is incorrect with react. Any help is greatly appreciated.
Conditionally render Cards or Signup based on truthy/falsey value of requestedPostsThatWeGotFromGecko.
render() {
const { requestedPostsThatWeGotFromGecko } = this.state;
return (
<div className="gecko">
{requestedPostsThatWeGotFromGecko ? (
<Cards />
) : (
<SignUp login={() => this.clickMe()} />
)}
</div>
);
}
Probably this is what you want:
render() {
return (
<div className='gecko'>
{!this.state.requestedPostsThatWeGotFromGecko &&
<SignUp login={() => this.clickMe()}/>
}
{this.state.requestedPostsThatWeGotFromGecko &&
<Cards />
}
</div>
);
}
If I understood correctly, you want to toggle between the Signup form and Cards based on requestedPostsThatWeGotFromGecko state variable.
So you can do something like this in your index.jsx:
render() {
return (
<div className='gecko'>
{this.state.requestedPostsThatWeGotFromGecko ?
<Cards /> :
<SignUp login={() => this.clickMe()} />
}
</div>
);
}
All you have to do is conditionally render the SignUp page on the basis of flag requestedPostsThatWeGotFromGecko.
Note: Important thing is you have to initialize it with false and make it true on the click from the SignUp page.
constructor(props) {
super(props);
this.state = { requestedPostsThatWeGotFromGecko: false };
this.clickMe = this.clickMe.bind(this)
}
render() {
const { requestedPostsThatWeGotFromGecko } = this.state;
return (
<div className="gecko">
{requestedPostsThatWeGotFromGecko ? (
<Cards />
) : (
<SignUp login={() => this.setState({ requestedPostsThatWeGotFromGecko: true })} />
)}
</div>
);
}
Related
I want on clicking the reply button the div to write the reply to come
I tried to create a seperate component for reply textarea but as I am a beginner in react I am not able to get an idea how to do it.
Comment.js
import Userdata from "./data.json";
import Score from "./Score";
import Person from "./person";
import Reply from "./Reply";
const Comment = () => {
return (<div className="sample">{
Userdata.comments.map((comment, index) => {
return (
<div key={comment.id}>
<div className="comment">
<Score score={comment.score} />
<div>
<Person user={comment.user} />
<span className="time">{comment.createdAt}</span>
<Reply index={index} />
<p>{comment.content}</p>
</div>
</div>
{comment.replies.map((reply) => {
return (
<div key={reply.id}>
<div className="comment reply">
<Score score={reply.score} />
<div>
<Person user={reply.user} />
<span>{reply.createdAt}</span>
<Reply />
<p>{reply.content}</p>
</div>
</div>
</div>
);
})}
</div>
);
})
}
</div>
);
}
export default Comment;
Reply Component
const Reply = (props) => {
const handleClick = () => {
console.log(`reply of ${props.index}`)
}
return (
<div onClick= {handleClick} className="btn-reply">
<img className="reply-icon" src="images/icon-reply.svg" alt="reply" />
<span>Reply</span>
</div>
);
}
export default Reply;
When i compile the app i get this warning in the console:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
My App.js:
import "./App.css";
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
toDoList: [],
activeItem: {
id: null,
title: "",
completed: false,
},
editing: false,
};
this.fetchTasks = this.fetchTasks.bind(this);
}
componentWillMount() {
this.fetchTasks();
}
fetchTasks() {
console.log("Fetching...");
fetch("http://127.0.0.1:8000/api/task-list/")
.then((response) => response.json())
.then((data) =>
this.setState({
toDoList: data,
})
);
}
render() {
var tasks = this.state.toDoList;
return (
<div className="container">
<div id="task-container">
<div id="form-wrapper">
<form id="form">
<div className="flex-wrapper">
<div style={{ flex: 6 }}>
<input
className="form-control"
type="text"
name="title"
placeholder="Add task"
/>
</div>
<div style={{ flex: 1 }}>
<input
className="btn btn-warning"
id="submit"
type="submit"
name="Add"
/>
</div>
</div>
</form>
</div>
<div className="list-wrapper">
{
(tasks.map = (task, index) => {
return (
<div key="{index}" className="task-wrapper flex-wrapper">
<span>{task.title}</span>
</div>
)})
}
</div>
</div>
</div>
);
}
}
export default App;
Basically i'm trying to list the items in the api list but i'm missing something. Anyone help me with it?
(tasks.map = (task, index) => {
return (
<div key="{index}" className="task-wrapper flex-wrapper">
<span>{task.title}</span>
</div>
)})
Should be:
(tasks.map(task, index) => {
return (
<div key="{index}" className="task-wrapper flex-wrapper">
<span>{task.title}</span>
</div>
)})
I'm working in a form with React. My idea is to create a reusable Form component that gets the state from a Page component as props, and will hold the logic for updating its own state with children data, send it to parent Page component.
The Page component is this:
class Page extends Component {
constructor(props) {
super(props);
this.state = {
data: {
text1: "Initial text1",
text2: "Initial text2"
}
};
}
render() {
return (
<div className="Page">
<div className="DataPreview">
Data preview in Page component
<div>{this.state.data.text1}</div>
<div>{this.state.data.text2}</div>
</div>
<Form data={this.state.data}>
<Input id="text1" data={this.state.data.text1} />
<Input id="text2" data={this.state.data.text2} />
</Form>
</div>
);
}
}
This is the Form component:
class Form extends Component {
constructor(props) {
super(props);
this.state = this.props.data;
}
render() {
return (
<div className="Parent">
<div>Form component</div>
<div className="DataPreview">
Data preview in Form component
<div>{this.state.text1}</div>
<div>{this.state.text2}</div>
</div>
{this.props.children}
</div>
);
}
}
And this the Input component:
class Input extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="Child" id={this.props.id}>
<div>Input component</div>
<input id={this.props.id} type="text" value={this.props.data} />
</div>
);
}
}
So Input should update Form state, and Form should update Page state. I know how to do it passing a callback when the Input is written Inside Form component, but I cant figure out how to do it when it is written inside Page component, like in this case.
I have a Sandbox for those interested: https://codesandbox.io/s/qx6kqypo09
class Input extends Component {
constructor(props) {
super(props);
}
handleChange(e) {
let data = this.props.this.state.data;
data.text1 = e.target.value;
this.props.this.setState({ data: data });
}
render() {
return (
<div className="Child" id={this.props.id}>
<div>Input component {this.props.id}</div>
<input
id={this.props.id}
type="text"
value={this.props.data}
onChange={e => this.handleChange(e)}
/>
</div>
);
}
}
use your input component as specified and your page component as mentioned below-
class Page extends Component {
constructor(props) {
super(props);
this.state = {
data: {
text1: "Initial text1",
text2: "Initial text2"
}
};
}
render() {
return (
<div className="Page">
<div className="DataPreview">
Data preview in Page component
<div>{this.state.data.text1}</div>
<div>{this.state.data.text2}</div>
</div>
<Form data={this.state.data}>
<Input id="text1" this={this} data={this.state.data.text1} />
<Input id="text2" data={this.state.data.text2} />
</Form>
</div>
);
}
}
I think this will help you
Thanks
As #dashton said, I am holding the same state in different components, and that's not correct. I will look for a different approach instead using only Form component state, and sharing logic via composition. I will open a new question for this.
without using some kind of state management, you would need to create a method that handles the state change in the parent component that you would then pass down to your child component a a prop.
Once you call that method in the child component it will update the state of the parent component.
This is one way of doing what you want to achieve: passing a callback handler for onChange. But, when your app starts to get bigger things can be ugly :) If you are thinking about creating a complex reusable Form component maybe you can examine the present node packages.
An alternative to this method, if you need a simple one, you can study React Context a little bit. It can help you maybe. Other than that Redux or other global state management libraries can do this also.
class Page extends React.Component {
state = {
data: {
text1: "Initial text1",
text2: "Initial text2",
},
};
handleChange = ( e ) => {
const { name, value } = e.target;
this.setState( prevState => ( {
data: { ...prevState.data, [ name ]: value },
} ) );
}
render() {
return (
<div className="Page">
<div className="DataPreview">
Data preview in Page component
<div>{this.state.data.text1}</div>
<div>{this.state.data.text2}</div>
</div>
<Form data={this.state.data}>
<Input name="text1" data={this.state.data.text1} onChange={this.handleChange} />
<Input name="text2" data={this.state.data.text2} onChange={this.handleChange} />
</Form>
</div>
);
}
}
const Form = props => (
<div className="Parent">
<div>Form component</div>
<div className="DataPreview">
Data preview in Form component
<div>{props.data.text1}</div>
<div>{props.data.text2}</div>
</div>
{props.children}
</div>
);
const Input = props => (
<div className="Child" id={props.id}>
<div>Input component {props.id}</div>
<input name={props.name} type="text" value={props.data} onChange={props.onChange} />
</div>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<Page />, rootElement);
.Page {
border: 10px solid blue;
}
.Parent {
border: 10px solid turquoise;
}
.Child {
border: 3px solid tomato;
}
.DataPreview {
border: 3px solid lightgray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
As other people have said, you are holding the same state in different components, which obviously isn't correct.
However, to answer your requirement regarding decoupling child components from the form, you could make your form handle state changes from the inputs by using a render prop which would pass a callback to the inputs, see code and link.
https://codesandbox.io/s/4zyvjm0q64
import React, { Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class Input extends Component {
constructor(props) {
super(props);
}
handleChange(id, value) {
this.props.onChange(id, value);
}
render() {
return (
<div className="Child" id={this.props.id}>
<div>Input component {this.props.id}</div>
<input
id={this.props.id}
type="text"
value={this.props.data}
onChange={e => this.handleChange(e)}
/>
</div>
);
}
}
class Form extends Component {
constructor(props) {
super(props);
this.state = this.props.data;
}
handleChange = (id, value) => {
this.setState({ [id]: value });
};
render() {
return (
<div className="Parent">
<div>Form component</div>
<div className="DataPreview">
Data preview in Form component
<div>{this.state.text1}</div>
<div>{this.state.text2}</div>
</div>
{this.props.render(this.handleChange)}
</div>
);
}
}
class Page extends Component {
constructor(props) {
super(props);
this.state = {
data: {
text1: "Initial text1",
text2: "Initial text2"
}
};
}
render() {
return (
<div className="Page">
<div className="DataPreview">
Data preview in Page component
<div>{this.state.data.text1}</div>
<div>{this.state.data.text2}</div>
</div>
<Form
data={this.state.data}
render={(handler) => {
return (
<div>
<Input id="text1" onChange={e => handler("text1", e.target.value)} />
<Input id="text2" onChange={e => handler("text2", e.target.value)} />
</div>
);
}}
/>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Page />, rootElement);
I have a simple component that displays data onClick event on a button. Here is my component:
import React, { Component } from 'react';
import './cardCheck.css';
class CardCheck extends Component {
constructor(props) {
super(props);
this.state = { showMessage: false };
}
_showMessage = bool => {
this.setState({
showMessage: bool
});
};
render() {
return (
<div>
<div className="newsletter-container">
<h1>Enter the ID of your card:</h1>
<div className="center">
<input type="number" />
<input type="submit" value="Check" onClick={this._showMessage.bind(null, true)} />
</div>
<div className="results" />
{this.state.showMessage && (
<div>
hello world!
<button onClick={this._showMessage.bind(null, false)}>hide</button>
</div>
)}
</div>
<h1>Offers:</h1>
</div>
);
}
}
export default CardCheck;
The code works, but I have this error in my console:
JSX props should not use .bind()
I read about it and changed my function to arrow ones like this:
import React, { Component } from 'react';
import './cardCheck.css';
class CardCheck extends Component {
constructor(props) {
super(props);
this.state = { showMessage: false };
}
_showMessage = bool => () => {
this.setState({
showMessage: bool
});
};
render() {
return (
<div>
<div className="newsletter-container">
<h1>Enter the ID of your card:</h1>
<div className="center">
<input type="number" />
<input type="submit" value="Check" onClick={this._showMessage()} />
</div>
<div className="results" />
{this.state.showMessage && (
<div>
hello world!
<button onClick={this._showMessage()}>hide</button>
</div>
)}
</div>
<h1>Offers:</h1>
</div>
);
}
}
export default CardCheck;
The error is gone, but my code does not work now. What is the correct way to do this with arrow functions and still make it work?
Either binding or using arrow function is not suggested since those functions will be recreated in every render. This is why you see those warnings. Instead of binding or invoking with an arrow function use it with reference and change your function a little bit.
_showMessage = () =>
this.setState( prevState => ( {
showMessage: !prevState.showMessage,
}) );
Instead of using a boolean, we are changing showMessage value by using its previous value. Here, we are using setState with a function to use previous state since setState itself is asynchronous.
And in your element you will use this function with its reference.
<input type="submit" value="Check" onClick={this._showMessage} />
Working example.
class CardCheck extends React.Component {
constructor(props) {
super(props);
this.state = { showMessage: false };
}
_showMessage = () =>
this.setState( prevState => ( {
showMessage: !prevState.showMessage,
}) );
render() {
return (
<div>
<div className="newsletter-container">
<h1>Enter the ID of your card:</h1>
<div className="center">
<input type="number" />
<input type="submit" value="Check" onClick={this._showMessage} />
</div>
<div className="results" />
{this.state.showMessage && (
<div>
hello world!
<button onClick={this._showMessage}>hide</button>
</div>
)}
</div>
<h1>Offers:</h1>
</div>
);
}
}
ReactDOM.render(
<CardCheck />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
<input type="submit" value="Check" onClick={this._showMessage()} />
You are invoking the _showMessage function by having the () in the onClick handler. You just want to pass the reference to the function, i.e. without ()
<input type="submit" value="Check" onClick={this._showMessage} />
I'm having a little bit of problem with wrapping my head around with passing states into parents. I need to send data from form container to app so that I can show updated states of list in weather info after submit
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Weather App</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<FormContainer label="Name of the city:"/>
<WeatherInfo
nameOfCity={this.state.nameOfCity}
weatherDescription={this.state.weatherDescription}
windSpeed={this.state.windSpeed}
temperature={this.state.temperature}
maxTemperature={this.state.maxTemperature}
minTemperature={this.state.minTemperature}
/>
</div>
);
}
}
export default App;
Form Container
class FormContainer extends Component {
constructor(props) {
super(props);
this.state = {
cityName: '',
nameOfCity:'',
weatherDescription:'',
windSpeed:'',
temperature:'',
maxTemperature:'',
minTemperature:''
};
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleCityName = this.handleCityName.bind(this);
}
handleFormSubmit(e) {
e.preventDefault();
const SendForm = {
cityName: this.state.cityName
};
console.log(SendForm);
fetch(`http://api.openweathermap.org/data/2.5/forecast/weather?q=${SendForm.cityName}&units=metric&APPID=********`)
.then(res => res.json())
.then(results => {
this.setState({
nameOfCity: results.city.name,
weatherDescription: results.list[0].weather[0].description,
windSpeed: results.list[2].wind.speed,
temperature: results.list[0].main.temp,
maxTemperature: results.list[0].main.temp_max,
minTemperature: results.list[0].main.temp_min
});
});
}
handleCityName(value) {
this.setState({ cityName: value });
}
render() {
return (
<div>
<form onSubmit={this.handleFormSubmit}>
<label>{this.props.label}</label>
<SearchBar
name="CityName"
type="text"
value={this.state.cityName}
placeholder="search"
onChange={this.handleCityName}
/>
<button type="submit"
className=""
value='Submit'
placeholder="Search" />
</form>
</div>
);
}
}
export {FormContainer};
Search bar component
const SearchBar = (props) => (
<div>
<label>{props.label}</label>
<input name={props.name} type={props.inputType} value={props.value} placeholder={props.placeholder} onChange={(e)=>props.onChange(e.target.value)}/>
</div>
);
export default SearchBar;
and Weather Info component
const WeatherInfo = (props) => (
<div>
<ul>
<li>{props.nameOfCity}</li>
<li>{props.weatherDescription}</li>
<li>{props.windSpeed}</li>
<li>{props.temperature}</li>
<li>{props.maxTemperature}</li>
<li>{props.minTemperature}</li>
</ul>
</div>
);
export default WeatherInfo;
You can pass method to update App state to FormContainer component
class App extends Component {
constructor() {
this.state = {
cityName: '',
nameOfCity:'',
weatherDescription:'',
windSpeed:'',
temperature:'',
maxTemperature:'',
minTemperature:''
};
}
updateInfo(results) {
this.setState({
nameOfCity: results.city.name,
weatherDescription: results.list[0].weather[0].description,
windSpeed: results.list[2].wind.speed,
temperature: results.list[0].main.temp,
maxTemperature: results.list[0].main.temp_max,
minTemperature: results.list[0].main.temp_min
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Weather App</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<FormContainer label="Name of the city:" updateInfo={this.updateInfo.bind(this)}
nameOfCity={this.state.nameOfCity}
/>
<WeatherInfo
nameOfCity={this.state.nameOfCity}
weatherDescription={this.state.weatherDescription}
windSpeed={this.state.windSpeed}
temperature={this.state.temperature}
maxTemperature={this.state.maxTemperature}
minTemperature={this.state.minTemperature}
/>
</div>
);
}
}
export default App;
And call it from FormComponent
class FormContainer extends Component {
constructor(props) {
super(props);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleCityName = this.handleCityName.bind(this);
}
handleFormSubmit(e) {
e.preventDefault();
const SendForm = {
cityName: this.props.cityName
};
console.log(SendForm);
fetch(`http://api.openweathermap.org/data/2.5/forecast/weather?q=${SendForm.cityName}&units=metric&APPID=********`)
.then(res => res.json())
.then(results => {
this.props.updateInfo(results);
});
}
handleCityName(value) {
// Do what you want to do, like resend API request or smth
}
render() {
return (
<div>
<form onSubmit={this.handleFormSubmit}>
<label>{this.props.label}</label>
<SearchBar
name="CityName"
type="text"
value={this.props.cityName}
placeholder="search"
onChange={this.handleCityName}
/>
<button type="submit"
className=""
value='Submit'
placeholder="Search" />
</form>
</div>
);
}
}
export {FormContainer};