Share State to other component | pass data to other component - reactjs

hello I'm currently learning about React, and I'm confused about how to pass data or state to another component
i have Search Component like this
function Search(props) {
const [ query, setQuery ] = useState("")
const [ movie, setMovie ] = useState({})
function searchHandler() {
axios.get(`${api.url}SearchMovie/${api.key}/${query}`)
.then(res => {
setMovie(res.data.results)
}).catch(err => {
console.log(err)
})
}
return (
<div className="search-input">
<div class="input-group input-custom mb-3">
<input
type="text"
class="form-control"
placeholder="Search Movie"
onChange={e => setQuery(e.target.value)}
value={query}
/>
<button
class="btn btn-outline-primary"
onClick={searchHandler}
>
Search
</button>
</div>
</div>
);
}
export default Search;
and also MainPage Component like this
function MainPage() {
return (
<div>
<Navbar />
<div className="container">
<Search />
<hr />
<div className="content">
<div className="row">
<div className="col-4">
<Card
image="https://dbkpop.com/wp-content/uploads/2020/06/weeekly_we_are_teaser_2_monday.jpg"
title="Monday"
description="Monday Weeekly Member"
/>
</div>
<div className="col-4">
<Card
image="https://dbkpop.com/wp-content/uploads/2020/06/weeekly_we_are_teaser_2_monday.jpg"
title="Monday"
description="Monday Weeekly Member"
/>
</div>
<div className="col-4">
<Card
image="https://dbkpop.com/wp-content/uploads/2020/06/weeekly_we_are_teaser_2_monday.jpg"
title="Monday"
description="Monday Weeekly Member"
/>
</div>
</div>
</div>
</div>
</div>
);
}
export default MainPage;
the problem is, how to pass State (movie) from Search Component to MainPage Component. so that I can render the data to MainPage Component

Data in React flows down, so you need to lift the state up.
Hence, the movie state should be in scope of MainPage:
function MainPage() {
const [ movie, setMovie ] = useState({})
// Set query results with setMovie
return <Search setMovie={setMovie} ... />
}
function Search(props) {
function searchHandler() {
axios.get(`${api.url}SearchMovie/${api.key}/${query}`)
.then(res => {
props.setMovie(res.data.results)
}).catch(err => {
console.log(err)
})
}
return (...);
}
export default Search;

Related

REACT JS FIREBASE FIRESTORE- how can i update my field in a document?

here is my manageexam.jsx file
this is where the update happen when i click the manage button on the table. i want to update a specific document id (3BelYq7lMxRNrWKknCRK- this is a sample of my document id but ofcourse there will be a lot of document id when i will add more inside the collection.) but i want to update the fields without manually adding the document Id that i want to update.
const ManageExam = () => {
const [description,setDesc]=useState("")
const [title,setTitle]=useState("")
function handleUpdate(e){
e.preventDefault();
const examcollref = doc(db,'Exams' "3BelYq7lMxRNrWKknCRK")
updateDoc(examcollref,{
title:title,
description:description
} ).then(response => {
alert("updated")
}).catch(error =>{
console.log(error.message)
})
}
return (
<div className="manageExam">
<Sidebar/>
<div className="manageExamContainer">
<div className="examInfo">
<h1>Manage Exam</h1>
</div>
<div className="left">
<div className="leftForm">
<div className="leftTitle">
Exam information
</div>
<br />
<div className="leftTitle">
</div>
<form onSubmit={handleUpdate}>
<label >Exam Title</label>
<input
type="text"
placeholder={title.doc}
value={title}
onChange={e => setTitle(e.target.value)}/>
<label htmlFor="">Description</label>
<textarea
id="desc"
cols="30"
rows="7"
value={description}
onChange={e =>setDesc(e.target.value)}
></textarea>
<button type="submit">Update</button>
</form>
</div>
</div>
<div className="right">
<div className="rightForm">
<div className="rightTitle">
Add Questions
<Link to= {`add_question`}style={{textDecoration:"none"}} className="link" >
Add new
</Link>
</div>
<div className="rightContainer">
{/* <p>1. What is the Meaning of db?</p> */}
{/* <div>
<input type="radio" name="option1" value="database" checked/>
<label htmlFor="">database</label>
</div>
<div>
<input type="radio" name="option2" value="data" disabled/>
<label htmlFor="">data</label>
</div>
<div>
<input type="radio" name="option3" value="databytes" disabled/>
<label htmlFor="">databytes</label>
</div>
<div>
<input type="radio" name="option4" value="databoard" disabled/>
<label htmlFor="">databoard</label>
</div>
<br />
<button>update</button>
<button>delete</button> */}
</div>
</div>
</div>
</div>
</div>
)
}
export default ManageExam
export const Examtable = ({id}) => {
const [list,setExamlist] = useState([])
// function to call the list from the firestore
useEffect (()=>{
const unsub = onSnapshot(
collection(db, "Exams"), //"exams -> pangalan ng database/("collection") ko"
(snapShot) => {
let list = [];
snapShot.docs.forEach((doc) => {
list.push({ id: doc.id, ...doc.data() });
});
setExamlist(list);
console.log(list.id);
},
(error) => {
console.log(error);
}
);
return () => {
unsub();
};
},[]);
const handleDelete = async (id) => {
alert("Do you want to delete?")
//window.confirm("Are you sure you want to delete?");
try {
await deleteDoc(doc(db, "Exams", id));
setExamlist(list.filter((item) => item.id !== id));
console.log(id)
} catch (err) {
console.log(err);
}
};
const actionColumn = [{field: "action", headerName: "Action", width: 200, renderCell:(params)=>{
return(
<div className="cellAction">
<div className="manageButton"> {/*/exam/manage_exam*/}
<Link to={`/exam/manage_exam/${params.row.id}`} style={{textDecoration:"none"}} className="link" >
Manage
</Link>
</div>
<div className="deleteButton" onClick={() => handleDelete(params.row.id)}>Delete</div>
</div>
)
}}];
return (
<div className="examtable" >
<div className="examtableTitle">
Exam
<Link to="/exam/new_exam/" style={{textDecoration:"none"}} className="link">
Add new
</Link>
</div>
<DataGrid
className="datagrid"
rows={list} //eto mga list nung nasa firebase
columns={examColumns.concat(actionColumn)}
pageSize={9}
rowsPerPageOptions={[9]}
checkboxSelection
/>
</div>
)
}
export default Examtable
here is the examtable.jsx where all the document in the collection will be displayed.
when i click the manage button, the url will display like this (localhost:3000/exam/manageexam/3BelYq7lMxRNrWKknCRK,, its because i click on this document but i cant update it at all because the console always said the id was undefined. i hope you understand what im saying
Because your pass id with Link in Examtable file.I think u must use useParams from react-router-dom in ur ManageExam.
First you need add id in your route path file, like this.
path: '/exam/manageexam/:id'
And then, in ur ManageExam.
import {useParams} from 'react-router-dom'
const ManageExam = () => {
const {id} = useParams()
const [description,setDesc]=useState("")
const [title,setTitle]=useState("")
function handleUpdate(e){
e.preventDefault();
const examcollref = doc(db,'Exams', id)
updateDoc(examcollref,{
title:title,
description:description
} ).then(response => {
alert("updated")
}).catch(error =>{
console.log(error.message)
})

Grabbing the Value of a Dynamically Created Object

I am dynamically creating buttons from an API call that looks like this:
My goal is that when a button is clicked the inner text will display in the search bar above.
below is the code for this auto complete component:
const Autocomplete = (props) =>
{
const btnSearch = (e) => {
console.log(props.suggestions)
}
return(
<>
{props.suggestions.map((e) => (
<button className={style.btn} onClick={btnSearch} key={e}>{e}</button>
))}
</>
);
}
export default Autocomplete;
The Autocomplete component is then being placed in a div as seen here:
return (
<>
<div className={style.container}>
<div className={style.title_hold}>
<h1>turn one</h1>
<h2>a search engine and game companion for Magic: The Gathering</h2>
</div>
<input className={style.search} type='text' placeholder='search for cards here...' value={search} onChange={handleInputChange} onKeyPress={handleSubmit}></input>
<div className={style.btn_wrap}>
<Autocomplete suggestions={results} />
</div>
<div className={style.data_wrap} id='user_display'>
<div className={style.img_wrap}>
{photos}
</div>
<div className={style.display_info}>
<h2>{card.name}</h2>
<h2>{card.type_line}</h2>
<h2>{card.oracle_text}</h2>
</div>
</div>
</div>
</>
)
Any help would be appreciated.
You can create a state variable in your parent component and then pass a function to the Autocomplete's button for the onClick which will then update the state in the parent. Something like this:
const Autocomplete = (props) => {
return(
<>
{props.suggestions.map((e) => (
<button className={style.btn} onClick={() => props.setSearch(e)} key={e}>{e}</button>
))}
</>
);
}
export default Autocomplete;
Your parent component:
import React from 'react'
const ParentComponent = (props) => {
const [searchText, setSearchText] = React.useState("")
const handleClick = (textFromButtonClick) => {
setSearchText(textFromButtonClick)
}
return (
<>
<div className={style.container}>
<div className={style.title_hold}>
<h1>turn one</h1>
<h2>a search engine and game companion for Magic: The Gathering</h2>
</div>
<input className={style.search} type='text' placeholder='search for cards here...' value={searchText} onChange={handleInputChange} onKeyPress={handleSubmit}></input>
<div className={style.btn_wrap}>
<Autocomplete setSearch={handleClick} suggestions={results} />
</div>
<div className={style.data_wrap} id='user_display'>
<div className={style.img_wrap}>
{photos}
</div>
<div className={style.display_info}>
<h2>{card.name}</h2>
<h2>{card.type_line}</h2>
<h2>{card.oracle_text}</h2>
</div>
</div>
</div>
</>
)
}
export default ParentComponent;
I took over your input value in the parent component, but without seeing any of your other code, I have no idea how you're managing that but you can likely merge it into this workflow to wire it up.

How to pass state properties from component to component

I am currently learning React and I am trying to create a basic todo list app. I am facing an issue in the understanding of how passing data from component to component.
I need that when I add a task in the modal of my home component it gets added in the "pub" state of my public task component in order for the task to be rendered.
I joined the code of both components,
Hope someone can help me :)
function PublicTask (){
const [pub,setPub] = useState([{id: 1, value : "test"},{id: 2, value : "test2"}]);
function ToDoPublicItem() {
const pubT = pub.map(value =>{
return(
<div className= 'pubTask-item'>
<li>{value.value}</li>
</div>
)
});
return(
<div>
<div>
{pubT}
</div>
</div>
);
}
return(
<div className= 'item-container'>
<h2 style={{color:'white'}}>Public Tasks</h2>
<ToDoPublicItem/>
</div>
);
}
export default PublicTask;
function Home() {
const [show,setShow] = useState(false);
const [pubTask,setPubTask] = useState([]);
function openModal() {
setShow(true);
}
function Modal(){
const[textTodo, setTextTodo] = useState('')
const addItem = () => {
const itemTopush = textTodo;
pubTask.push(itemTopush);
}
return(
<div className='modal'>
<div className = 'modal-title'>
<h2>ADD A TODO</h2>
<hr></hr>
</div>
<div className= 'modal-body'>
<input type='text' onChange = {(e) => setTextTodo(e.target.value)}/>
<input type="checkbox" id="pub" value ='public'/>
<label Htmlfor="pub">Public</label>
<input type="checkbox" id="priv" value= 'private '/>
<label Htmlfor="riv">Private</label>
<hr></hr>
<Button id='button-add' size='large' style={{backgroundColor : 'white'}} onClick={()=> addItem()}>ADD</Button>
<hr></hr>
<Button id='button-close' size='large' style={{backgroundColor : '#af4c4c'}} onClick= {()=> setShow(false)} >CLOSE</Button>
</div>
</div>
)
}
return(
<div>
<h1 style={{textAlign:'center'}}>You are logged in !</h1>
<div>
<button id='button-logout' onClick = {() => firebaseApp.auth().signOut()}>Logout</button>
</div>
<div>
<Fab color="primary" aria-label="add" size = 'large' onClick = {() => openModal()}>
<Add/>
</Fab>
{show ? <Modal/> : <div></div>}
</div>
<div>
<Router>
<div className='pub-container'>
<Link to='/publicTasks'>Public Tasks </Link>
</div>
<div className='ongo-container'>
<Link to='/onGoingTasks'>On Going Tasks </Link>
</div>
<div className='finish-container'>
<Link to='/finishedTasks'>Finished Tasks </Link>
</div>
<Route path='/publicTasks' component = {PublicTask}/>
<Route path='/onGoingTasks' component = {OngoingTask}/>
<Route path='/finishedTasks' component = {FinishedTask}/>
</Router>
</div>
</div>
);
}
export default Home;
You can share data between react components like this:
const [value, setValue] = useState("test"); // data that you want to share
return (
<Parent data={value}> // pass data to parent in your child component
);
<h1>{this.props.data}</h1> // do something with the data in the parent component

I want to use react hook 'useState' to save the information fetched from API and show on the scrren. But, I can't use in class so what can I do?

So, for some context I'm fetching some search results on click on search button. The result shows in console.log() after clicking search button perfectly. the SearchComponent.js is below.
import React, { Component, useState } from 'react'
import { API_KEY, API_URL } from '../config/keys';
import { Link } from 'react-router-dom';
class SearchBox extends Component {
constructor(props) {
super(props);
this.state = {
searchQuery: ""
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.onChangeValue = this.onChangeValue.bind(this);
}
handleChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
this.setState({ [name]: value });
}
handleSubmit = (e) => {
e.preventDefault();
var data = this.state.searchQuery;
const url = `${API_URL}search/${this.state.selectedOption}?api_key=${API_KEY}&language=en-US&query=${encodeURI(data)}&page=1&include_adult=false`;
fetch(url)
.then(response => response.json())
.then(response => {
console.log(response);
const result = response.results;
})
}
onChangeValue(event) {
this.setState({
selectedOption: event.target.value
});
}
render() {
return (
<>
<div className="mt-3">
{/* Breadcrumb */}
<div style={{ width: '95%', margin: '1rem auto' }}>
<nav aria-label="breadcrumb">
<ol className="breadcrumb">
<li className="breadcrumb-item"><Link to='/'>Home</Link></li>
<li className="breadcrumb-item active" aria-current="page">Search</li>
</ol>
</nav>
</div>
<div className="row">
<div className="col-6 offset-3">
<form className="form-group">
<div className="input-group">
<input
className="form-control"
type="text"
placeholder= 'Search...'
onChange={this.handleChange}
name= 'searchQuery'
value={this.state.searchQuery} />
<button onClick={this.handleSubmit} type="submit" className="btn btn-primary input-group-addon" ><span className="fa fa-search fa-lg"></span></button>
</div>
{/* radio buttons */}
<div className="mt-2">
<div class="form-check">
<input
class="form-check-input"
type="radio"
name="movie"
value="movie"
checked={this.state.selectedOption === "movie"}
onChange={this.onChangeValue}
/>
<span class="form-check-label font-weight-bold">
Movies
</span>
</div>
<div class="form-check">
<input
class="form-check-input"
type="radio"
value="tv"
name="tvshow"
checked={this.state.selectedOption === "tv"}
onChange={this.onChangeValue}
/>
<span class="form-check-label font-weight-bold">
TV Shows
</span>
</div>
</div>
</form>
</div>
</div>
</div>
{/* search results */}
<div style={{ width: '95%', margin: '1rem auto' }}>
<div className="text-center">
<div className="font-weight-lighter h2"> Search Results </div>
</div>
</div>
</>
)
}
}
export default SearchBox;
the array of result is in result variable of handleSubmit(). how can I use useState to store my result var and then show it on scrren.
if you don't understand how i'm talking about using this hook i've attached a file which does similar thing.
landingComponent.js
import React, { useEffect, useState } from 'react';
import {API_URL, API_KEY, IMAGE_URL} from '../../config/keys';
import { Row } from 'reactstrap';
import MainImage from './MainImage';
import GridCard from './GridCard';
import { Link } from 'react-router-dom';
function LandingPage() {
const [Movies, setMovies] = useState([]);
const [CurrentPage, setCurrentPage] = useState(0);
useEffect( () => {
const endpoint = `${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`;
fetchMovies(endpoint);
}, []);
const fetchMovies = (path) => {
fetch(path)
.then(response => response.json())
.then(response => {
console.log(response);
setMovies([...Movies, ...response.results]);
setCurrentPage(response.page);
})
}
const handleClick = () => {
const endpoint = `${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=${CurrentPage + 1}`
fetchMovies(endpoint);
}
return (
<div style={{ width: '100%', margin: 0 }} >
<div style={{ width: '95%', margin: '1rem auto' }}>
{/* Breadcrumbs */}
<nav aria-label="breadcrumb">
<ol className="breadcrumb">
<li className="breadcrumb-item"><Link to='/'>Home</Link></li>
<li className="breadcrumb-item active" aria-current="page">Movies</li>
</ol>
</nav>
<div className="font-weight-bold h2"> Latest Movies </div>
<hr style={{borderColor:'black'}}/>
<Row>
{Movies && Movies.map((movie, index) => (
<React.Fragment key={index}>
<GridCard
image={movie.poster_path && `${IMAGE_URL}w500${movie.poster_path}`}
movieId={movie.id} movieTitle={movie.title} name={movie.original_title}
/>
</React.Fragment>
))}
</Row>
<br />
<div className="text-center">
<button className="btn btn-primary" onClick={handleClick}> Load More </button>
</div>
</div>
</div>
)
}
export default LandingPage
I want to use same way in SearchComponent.js. I tried so many thing but none worked. Help is appreciated.
React has two ways of using components :
Class components
Declared this way : class ComponentName extends Component {
then your state is managed using : this.setState()
Function components
Declared just as a function as your second example
There you can use hooks and the useState()
So if you're not planning to re-write all your component you'll have to use this.setState()
When you fetch the data you need to store it in the state again creating results:[] property in the state.
handleSubmit = (e) => {
e.preventDefault();
var data = this.state.searchQuery;
const url = `${API_URL}search/${this.state.selectedOption}?api_key=${API_KEY}&language=en-US&query=${encodeURI(data)}&page=1&include_adult=false`;
fetch(url)
.then(response => response.json())
.then(response => {
console.log(response);
const result = response.results;
this.setState({results:result}); //Here you store the state.
});
}
Now you will have to show it in the results JSX block.
{/* search results */}
<div style={{ width: '95%', margin: '1rem auto' }}>
<div className="text-center">
<div className="font-weight-lighter h2"> Search Results </div>
<div className="results">
<ul>
{this.state.results.length && this.state.results.map(item => { return (
<li> {item} </li>
) })}
</ul>
</div>
</div>
</div>

why the component is getting unmounted and mounter everytime when the state is changed

Home.JS
class Home extends Component{
state = {
serverPosts:null,
offlinePosts:[],
isLoading:false,
isError:false,
error:null
}
componentDidMount(){
console.log("home did mount")
this.setState({isLoading:true})
axios.get('https://jsonplaceholder.typicode.com/posts')
.then((response)=>{
this.setState({
serverPosts:response.data,
isLoading:false
})
}).catch((err)=>{
this.setState({
isError:true,
error:err
})
})
}
addOfflinePost = (post) => {
const offlineList = [...this.state.offlinePosts,{post}]
this.setState({offlinePosts:offlineList})
}
render(){
console.log("Home component render")
let serverPostList = (this.state.serverPosts)?
this.state.serverPosts.map((item,index)=>{ return <Post postData = {item} key={index}/>}):
(this.state.isError)?<p>No Internet Connection</p>:<p>No Post available</p>
let offlinePostList = (this.state.offlinePosts)?
this.state.offlinePosts.map((item, index)=>{ return <Post postData = {item} key={`id-${index}`}/>}):<button className="btn btn-primary mx-auto" onClick={this.mainContentHandler}>Add Post</button>;
return(
<div className={classes.Home}>
<div className="row py-2">
<div className="col-lg-4">
<div className={"row "+ classes.OfflineList}>
</div>
<div className={"row "+ classes.ServerList}>
{serverPostList}
</div>
</div>
<div className="col-lg-8">
<PostForm click = {this.addOfflinePost}/>
</div>
</div>
</div>
)
}
}
export default Home;
AddForm.JS
class PostForm extends Component{
state = {
title:null,
content:null
}
titleChangeHandler = (event) => {
this.setState({title:event.target.value})
}
contentChangeHandler = (event) => {
this.setState({content:event.target.value})
}
render(){
return (
<div className="card card-primary">
<div className="card-header">
POST
</div>
<div className="card-body">
<form>
<div className="form-group">
<div className="form-group">
<input className="form-control" type="text" placeholder="Title" onChange={this.titleChangeHandler}/>
</div>
<div className="form-group">
<input className="form-control" type="text" placeholder="Content" onChange={this.contentChangeHandler}/>
</div>
<div className="form-group">
<button className="btn btn-primary btn-block" onClick={()=>this.props.click(this.state)}>Submit</button>
</div>
</div>
</form>
</div>
</div>
)}
}
export default PostForm;
Q1. The render function is running multiple times when the component get loaded. When i submit the form then the componentDidMount is running everytime. Please explain me how the flow is working in this component.
Q2. Also if you help me with the best practice of using bootstrap and manual styling together in react

Resources