I am trying to create a simple SPA (without Router). It has also a simple structure: a component per section:
Home
Services
Products
Product
Modal
Contact us
As you can see the component Products has two sub-components Product and Modal. These are iterated so many times as JSON objects there are:
Products.js
import React, { Component } from "react";
import ReactHtmlParser from "react-html-parser";
import "./Products.css";
import { products } from "./products.json";
import Product from "./Product/Product";
import Modal from "./Modal/Modal";
class Products extends Component {
render() {
return (
<section id='products'>
<div className='container'>
<div className='row'>
{products.map(product => {
return (
<div>
<Product
image={"/img/" + product.image}
name={product.name}
target={product.target}
/>
<Modal
id={product.target}
title={product.name}
body={ReactHtmlParser(product.body)}
/>
</div>
);
})}
</div>
</div>
</section>
);
}
}
export default Products;
Each product has a More Info button what opens the modal and this has another button Budget ("Presupuestar"):
That function should "change the state" of Contact us component (a simple contact us form):
The component has the following code:
Contact.js
import React, { Component } from "react";
import "./Contact.css";
class Contact extends Component {
constructor() {
super();
this.state = { budget: "Contact" };
}
render() {
return (
<section id='contact'>
<div className='container'>
<div className='row'>
<div className='col-xs-12 col-md-6'>
<div className='contact-form'>
<form>
...
{/* Subject */}
<div className='form-group'>
<div className='input-group'>
<span className='input-group-addon' />
<input
type='text'
className='form-control'
id='subject'
aria-describedby='Subject'
placeholder='Subject'
readonly='readonly'
value={this.state.budget}
/>
</div>
{/* /form-group */}
</div>
{/* /Subject */}
...
</form>
</div>
</div>
</div>
</div>
</section>
);
}
}
I guess then I should create a function in the Modal component to trigger with an onClick="setSubject" in the Budget ("Presupuestar") button. What I don't know is how to alter the other component's state.
A quick summary: I have to make the following state update:
I was reading this similar question but I didn't get how to apply in my scenario. Any ideas?
I think you should either but the clickHandler function of the button in the App component that wrap the whole components and then pass it to the Products component then to Modal component but it's not a good practice,
Or you can use Redux a state management system that let you control your state through the whole app.
First of all, you don't need a function to change the state of another component. The smart way to do that is using an intermediary thing to connect 2 component together. There is two way to solve this problem.
The easiest way is you can transfer subject via URL (URL is "the intermediary thing"). When you click the button Presupuestar you can change URL to page contact like this:
/contact?subject=whatever you want
Then, at Contact component, you just need to parse URL to get subject (you can see this question to know how to parse from URL). You can see my example.
The second way is creating a service use singleton pattern to transfer subject from Modal to Contact form. You can see my example.
You can achieve this like this
Create a main app component which will contain all these these three comps
Add a function in app component "changeContacts"
Send it to both the product as well as contacts
Here is an explanation
class App extends Component {
render() {
return (
<div>
<Contact ref="contacts"/>
<Products changeContacts={this.changeContacts} />
</div>
);
}
changeContacts = (newState) => {
this.refs.contacts.changeState(newState)
};
}
class Contact extends Component {
state = { text:"Old Text" }
render() {
return ( <div style={{fontSize:50,backgroundColor:'red'}}>{this.state.text}</div> );
}
changeState = (newState) =>{
this.setState(newState);
}
}
class Modal extends Component {
render() {
return ( <div onClick={() => this.props.onClick({text:"New State Text"})}>This is a modal</div> );
}
}
class Products extends Component {
state = { }
render() {
return ( <div>
<h1>Products List</h1>
<Modal onClick={this.props.changeContacts} />
<Modal onClick={this.props.changeContacts}/>
<Modal onClick={this.props.changeContacts}/>
</div> );
}
}
Related
This is the same app/continuation of this previous question: Invalid hook call trying to make an axios get request in react
Currently, I'm trying to figure out the best way to conditionally render a component and pass values from my API calls to it. I'll try to explain the current set up of the app the best I can. Here is a link of the non-react version for some visuals: https://giovannimalcolm.github.io/weather-dashboard/
I plan to have a component for the page before any input is submitted. The component I'm working on now is for the current weather box that appears once a city is submitted. I will make a third component for the five forecast cards below the aforementioned.
Currently, in the Home component, I have a onClick on the search button to show the current weather component when clicked. I will probably change this to onSubmit and later add an autocomplete function to the search box for not only more precise results but to also prevent submissions of poor formatting or null submissions. I believe the weather will data will always return with something in this case. The Home component is shown below
import React, { Component } from 'react';
import {Weather} from '../components/TodaysWeather'
import { getWeatherData } from '../service/getWeather';
import { GetWeatherUrl } from '../service/getWeatherUrl';
export class Home extends Component {
constructor(props){
super(props);
this.state = {
location: "",
showWeather: false
};
this.locationChange = this.locationChange.bind(this);
}
onSubmit(e) {
e.preventDefault();
}
locationChange(e){
this.setState({
location: e.target.value
});
}
_showWeather = async (bool) => {
this.setState({
showWeather: bool
});
await getWeatherData(this.state.location)
console.log(await GetWeatherUrl(this.state.location))
}
componentDidUpdate(){
console.log(this.state)
}
render() {
return (
<div>
<header className="main-header">
<h1>Weather Dashboard</h1>
</header>
<div className="container-fluid" style={{ maxWidth: '1400px' }}>
<div className="row">
<aside className="col-lg-3 pb-3">
<h2 id="sidebar-title">Search for a City:</h2>
<form onSubmit={e => this.onSubmit(e)} id="citySearch">
<div className="input-group">
<input
className="form-control"
type="text"
placeholder="City Here"
id="city-input"
onChange={this.locationChange }
/>
<div className="input-group-append"></div>
</div>
<button
type="submit"
className="btn btn-primary btn-block"
id="sidebar-btn"
onClick={this._showWeather.bind(null,true)}
>
Search
</button>
</form>
<div id="history"></div>
</aside>
</div>
</div>
</div>
)
}
}
I have API calls to get the weather data in a separate "service" folder. These are called in the Home component in the _showweather function. What I need help with is figuring out the best way to capture the data from the API call in Home and send it over to the TodaysWeather component (and later the Forecast component) so it can be used for conditionally rendering via states and rendering in the virtual DOM.
I've considered doing the API call in the TodaysWeather component as shown below but this won't work as I need the data to be pulled before any rendering.
import { GetWeatherUrl } from "../service/getWeatherUrl";
import Axios from 'axios';
import React, { Component } from 'react';
export class Weather extends Component {
state = {
loading: true,
weather: []
}
async componentDidMount(){
const res = await Axios.get(GetWeatherUrl());
this.setState({weather: res.data, loading: false})
console.log(this.state.weather);
}
render(){
return(
<div>
<div className="col-lg-9 pb-3">
<section id="presentDay" className="todaysWeather">
<div className="todaysWeather-body">
<h2 className="h3 today-title"> San Diego <img className="weather-img" src="https://openweathermap.org/img/w/03d.png" alt="scattered clouds" /></h2>
<p className="today-txt">Temp: </p>
<p className="today-txt">Wind: 11.5 MPH</p>
<p className="today-txt">Humidity: 61 %</p>
<p>UV Index: <button className="uvi-btn wary-uvi">3.1</button>
</p></div>
</section>
</div>
</div>
)
}
}
Is there a better way to set this all up? Please ignore the strings in the render section, it only was there for debugging.
I'am very new in the programming world and React (using the COVID-19 time to get better...). I'm trying to render a component when the user is clicking a register button. My goal is to display it as a pop-up in the middle of the screen for the user to fill a form. (I'm using Visual studio code and react app generator)
I can't make it happen, if I console.log the result true/false ( depending on a condition) it works correctly so I guess the problem is the way I " call" the component.
If anyone could point toward the good direction I would glady appreciate !
The App class where the handler function is calling the supposed popup div
import React from "react"
import Header from "./UI/Header";import RegisterWindow from "./UI/RegisterWindow"; import Footer from "./UI/Footer"; import MainSection from "./UI/MainSection";
import "./index.css"
class App extends React.Component{
constructor(){
super()
this.state ={
registerIsShowed: false
}
this.handleRegister = this.handleRegister.bind(this)
}
handleRegister(){
this.setState({
registerIsShowed: !this.state.registerIsShowed
})
const isShowed = this.state.registerIsShowed;
return isShowed ? <RegisterWindow /> : null
}
render(){
return (
<div>
<Header register={this.handleRegister} />
<MainSection />
</div>
)}
}
export default App
This is the Header code where the button that triggers the opening is located
import React from "react"
function Header(props) {
return (
<header>
<nav className="navbar-header">
<p className="header-data"></p>
<ul className="navbar-menu-header">
<li><button onClick={props.register}>Registrar</button></li>
<li><button>Entrar</button></li>
</ul>
</nav>
</header>
)
}
export default Header
and finally the Component that is supposed to show up
import React from "react"
class RegisterWindow extends React.Component{
render(){
return (
<div className="register-window">
<div>
<form>
<input name="firstName" placeholder="First name" type="text" />First Name
<input name="lasttName" placeholder="Last name" type="text" />Last Name
</form>
</div>
</div>
)
}
}
export default RegisterWindow
thank you,
The RegisterWindow component must be included in the Render lifecycle function in a class component, or within a return statement of a functional component. Your App component is class based so it must contain a render() method.
Setting the state is asynchronous, so even if you could render the component from the handleRegister() callback in a class component, the state update wouldn't be immediate so your synchronous logic to display the RegisterWindow component would fail.
Try something like this:
handleRegister() {
this.setState({
registerIsShowed: !this.state.registerIsShowed
});
}
render() {
return (
<>
{this.state.registerIsShowed && <RegisterWindow />}
<div>
<Header register={this.handleRegister} />
<MainSection />
</div>
</>
)
}
this.state.registerIsShowed && <RegisterWindow /> is an example of Conditional Rendering.
To make the RegisterWindow appear floating above the MainSection, you can style it with an absolute position.
I'm learning React using JSX and ES6 and I've got a pretty decent handle on how to create components and route to different views using ReactRouter4.
What I still haven't been able to figure out is for example how i can create an Admin page where I input the details of a work for my portfolio and have all the works render on the another page, presumably Portfolio page.
Here's what I've got.
App.js loads the Portfolio.js component
import React from 'react';
import Navigation from './Navigation';
import Title from './Title';
import Portfolio from './Portfolio';
class App extends React.Component {
render() {
return(
<div className="container-fluid">
<div className="container">
<div className="row">
<div className="col-sm-12">
<Navigation />
<Title title="kuality.io"/>
<section className="app">
<Portfolio works={this.props.works} />
</section>
</div>
</div>
</div>
</div>
)
}
}
export default App;
The Portfolio.js component has a constructor to bind a unique method named addWork(), the React methods componentWillMount() and componentWillUnmount() to handle state, and the default render(). One more thing to mention about this component is that it's calling a component called ../base which has all the details to an online DB via Firebase. So if that's relevant as to where it is place, then take that into consideration otherwise don't sweat it.
import React from 'react';
import Work from './Work';
import Admin from './Admin';
import base from '../base';
class Portfolio extends React.Component {
constructor() {
super();
this.addWork = this.addWork.bind(this);
// getInitialState
this.state = {
works: {}
};
}
componentWillMount() {
this.ref = base.syncState(`/works`
, {
context: this,
state: 'works'
})
}
componentWillUnmount() {
base.removeBinding(this.ref);
}
addWork(work) {
// update our state
const works = {...this.state.works};
// add in our new works with a timestamp in seconds since Jan 1st 1970
const timestamp = Date.now();
works[`work-${timestamp}`] = work;
// set state
this.setState({ works });
}
render() {
return(
<div>
<section className="portfolio">
<h3>Portfolio</h3>
<ul className="list-of-work">
{
Object
.keys(this.state.works)
.map(key => <Work key={key} details={this.state.works[key]}/>)
}
</ul>
</section>
</div>
)
}
}
export default Portfolio;
Inside of the Object i'm mapping through the Work component that is just a list item I have made another component for and isn't really relevant in the question.
Finally I have the Admin.js and AddWorkForm.js components. I abstracted the AddWorkForm.js so that I could use it elsewhere if need be, basically the main idea behind React Components, so that's why I chose to do it that way.
import React from 'react';
import Title from './Title';
import AddWorkForm from './AddWorkForm';
class Admin extends React.Component {
constructor() {
super();
this.addWork = this.addWork.bind(this);
// getInitialState
this.state = {
works: {}
};
}
addWork(work) {
// update our state
const works = {...this.state.works};
// add in our new works with a timestamp in seconds since Jan 1st 1970
const timestamp = Date.now();
works[`work-${timestamp}`] = work;
// set state
this.setState({ works });
}
render() {
return(
<div className="container-fluid">
<div className="container">
<div className="row">
<div className="col-sm-12">
<Title title="Admin"/>
<section className="admin">
<AddWorkForm addWork={this.addWork} />
</section>
</div>
</div>
</div>
</div>
)
}
}
export default Admin;
and the AddWorkForm.js component which is basically a form that onSubmit creates and object and resets the form
import React from 'react';
class AddWorkForm extends React.Component {
createWork(event) {
event.preventDefault();
console.log('Creating some work');
const work = {
name: this.name.value,
desc: this.desc.value,
image: this.image.value
}
this.props.addWork(work);
this.workForm.reset();
}
render() {
return(
<form ref={(input) => this.workForm = input} className="work-edit form-group" onSubmit={(e) => this.createWork(e)}>
<input ref={(input) => this.name = input} type="text" className="form-control" placeholder="Work Title"/>
<textarea ref={(input) => this.desc = input} type="text" className="form-control" placeholder="Work Description"></textarea>
<input ref={(input) => this.image = input} type="text" className="form-control" placeholder="Work Image"/>
<button type="submit" className="btn btn-primary">+Add Work</button>
</form>
)
}
}
export default AddWorkForm;
Here is the file that includes where I'm using ReactRouter:
import React from 'react';
import { render } from 'react-dom';
// To render one method from a package user curly brackets, you would have to know what method you wan though
import { BrowserRouter, Match, Miss} from 'react-router';
import './css/normalize.css';
import './css/bootstrap.css';
import './css/style.css';
// import '../js/bootstrap.js';
import App from './components/App';
import WorkItem from './components/WorkItem';
import Capability from './components/Capability';
import Connect from './components/Connect';
import NotFound from './components/NotFound';
import Admin from './components/Admin';
const Root = ()=> {
return(
<BrowserRouter>
<div>
<Match exactly pattern="/" component={App} />
<Match pattern="/work/:workId" component={WorkItem} />
<Match exactly pattern="/capability" component={Capability} />
<Match exactly pattern="/connect" component={Connect} />
<Match exactly pattern="/admin" component={Admin} />
<Miss component={NotFound} />
</div>
</BrowserRouter>
)
}
render (<Root />, document.querySelector('#main'));
So here's what I've tried and failed to accomplish, and it's likely some kind of this.props solution that I haven't been able to define, I need to create the work in Admin.js component, which creates the object and then have it throw that object to Portfolio.js component so it can render it via the Work.js component and it doesn't add the object to the DB.
This works when i put all the components on the same page, which isn't ideal because then anyone accessing my Portfolio could add a work. Sure I could start the process of learning authentication and how to make that component appear or disappear based on user credentials, but I'd much rather also learn the very valuable skill of being able to have my admin page on a separate view all together because I see another application for learning to do so.
Would love to hear others opinions on this and where they may be able to determine I'm failing here.
Btw, I realize I have other components like Nav.js and Title.js but they are not necessary in order to illustrate the example.
Thank you.
You can pass components as props and when using React Router you can have named components.
For data sharing between siblings is better advised to have the data on a parent component although you could use context, but this is not advised and may be unacessible on future versions.
If you need to create something on another component (don't know why) you could pass a function that would render it.
My React app has several similar custom buttons that perform different tasks. The UI is similar among all the buttons, what changes is the action each one must trigger and the title.
The working code for the parent Component containing the buttons is (similar) to the following:
class Page extends Component {
constructor(props) {
super(props);
}
action1(){
//... do stuff...
}
action2(){
//... do stuff...
}
render(){
return(
<div className="table-row">
<div className="table-cell">
<div className="button"
onClick={this.action1.bind(this)}>{"button1"}
</div>
</div>
<div className="table-cell">
<div className="button"
onClick={this.action2.bind(this)}>{"button2"}
</div>
</div>
</div>
);
}
}
Is it possible to pass a method to the child component the same way it is done for a variable value? I want to turn it into something like this:
class Page extends Component {
constructor(props) {
super(props);
}
action1(){
//... do stuff...
}
action2(){
//... do stuff...
}
render(){
return(
<div className="table-row">
<div className="table-cell">
<CustomButton action={this.action1.bind(this)} title={"button1"}/>
</div>
<div className="table-cell">
<CustomButton action={this.action2.bind(this)} title={"button2"}/>
</div>
</div>
);
}
}
class CustomButton extends Component{
constructor(props){
super(props);
}
render() {
return (
<div className="table-cell"><div className="button"
onClick= {this.props.action}>{this.props.title}
</div>
);
}
}
What would be the correct way to handle this situation and the theory behind it?
I'm using React with Meteor, in case it makes a difference.
You can pass props to components. Passed props can have any data type of javascript.
In your case, you want to pass an action props which has a function as the value. Then you access action props in your component and use it.
In short, there is no theory behind it. What you are doing is correct. This is how react handles passing data to other components. Note that this is not the only way to pass data to child components.
I am creating a basic blog in react using Flux + React Router + Firebase. I am having trouble trying to get a single blog post to render. When I click on the link to a single post, I try to filter out all of the other posts from a list of all posts and display only a single post from my firebase database.
I attempt to do this by matching the key of the firebase entry with the url params like so if (this.props.routeParams.key===key) . I really do not know what I have to do to make this happen. Any suggestions are welcome.
Below is Blogger.jsx, the page where I allow a user to create a blog post and then beneath the blog post, I display a list of the titles all blog posts.
import AltContainer from 'alt-container';
import React from 'react';
import { Link } from 'react-router';
import List from './List.jsx'
import Firebase from 'firebase'
import BlogStore from '../stores/BlogStore'
import BlogActions from '../actions/BlogActions';
const rootURL = 'https://incandescent-fire-6143.firebaseio.com/';
export default class Blogger extends React.Component {
constructor(props) {
super(props);
BlogStore.getState();
BlogStore.mountFirebase();
{console.log(this.props.location.query)}
};
componentDidMount() {
BlogStore.listen((state) => {
this.setState(state)
})
this.firebaseRef = new Firebase(rootURL + 'items/');
}
componentWillMount() {
BlogStore.unlisten((state) => {
this.setState(state)
})
}
renderList = (key) => {
return (
<Link to={`blogshow/${key}`}> <List key={key} blog={this.state.blog[key]} /> </Link>
)
}
handleInputChange = () => {
BlogStore.setState({
title: this.refs.title.value,
text: this.refs.text.value});
}
handleClick = () => {
BlogStore.handleClick();
}
render() {
return (
<div>
<div className="row panel panel-default">
<div className="col-md-8 col-md-offset-2">
<h2>
Create a New Blog Post
</h2>
</div>
</div>
<h2>Blog Title</h2>
<div className="input-group">
<input
ref="title"
value={BlogStore.state.title}
onChange = {this.handleInputChange}
type="text"
className="form-control"/>
<span className="input-group-btn">
</span>
</div>
<h2>Blog Entry</h2>
<div className="input-group">
<textarea
ref="text"
value={BlogStore.state.text}
onChange = {this.handleInputChange}
type="text"
className="form-control"/>
</div>
<div className="blog-submit input-group-btn">
<button onClick={this.handleClick}
className="btn btn-default" type="button">
Publish Blog Post
</button>
</div>
{/*<List blog={this.state.blog} />*/}
{Object.keys(BlogStore.state.blog)
.map(this.renderList)}
</div>
);
}
}
When a user clicks on a link to a single blog post, they should be transported to a page which shows only that single blog post. I have called this component BlogShow. I can't get BlogShow to render because I keep on getting the error
invariant.js?4599:45 Uncaught Invariant Violation: BlogShow.render(): A
valid React element (or null) must be returned. You may have returned
undefined, an array or some other invalid object.
This is BlogShow.jsx:
import AltContainer from 'alt-container';
import React from 'react';
import { Link } from 'react-router';
import Blogger from './Blogger'
import List from './List'
const rootURL = 'https://incandescent-fire-6143.firebaseio.com/';
import BlogStore from '../stores/BlogStore'
import BlogActions from '../actions/BlogActions';
export default class BlogShow extends React.Component {
constructor(props) {
super(props);
{console.log(this.props.routeParams.key)}
this.filterList = this.filterList.bind(this);
}
filterList(key) {
if (this.props.routeParams.key===key) {
return (<List key={key} blog={BlogStore.state.blog[key]} />)
}
}
render() {
<div> {Object.keys(BlogStore.state.blog).map(this.filterList)} </div>
}
}
You are getting that error because your Component BlogShow is not returning anything.
render() {
<div> {Object.keys(BlogStore.state.blog).map(this.filterList)} </div>
}
Should be:
render() {
return <div> {Object.keys(BlogStore.state.blog).map(this.filterList)} </div>
}
I'm not familiar with React.js at all, but I am familiar with pure JS arrays. To remove elements from an array, you should use .filter(), and then afterwards you can map the items.
Something like this:
filterList(key) {
return this.props.routeParams.key === key; // true if the item should stay in the list
}
mapList(key) {
return <List key={key} blog={BlogStore.state.blog[key]} />;
}
render() {
return <div> {Object.keys(BlogStore.state.blog).filter(this.filterList).map(this.mapList)} </div>;
}