Why props render as undefined? - javascript

I have this React-component called PersonCard:
class PersonCard extends Component {
constructor(props) {
super(props);
console.log(JSON.stringify(props));
this.state = props;
}
render() {
return (
<div>
<MuiThemeProvider muiTheme={Mui} >
<Card>
<CardHeader
title={this.props.firstName}
/>
</Card>
</MuiThemeProvider>
</div>
);
}
}
export default PersonCard;
The view has multiple PersonCards and they're mapped from an array in its parent component SearchResults as follows:
class SearchResults extends Component {
constructor() {
super()
this.state = {
data: [],
}
}
componentDidMount() {
return fetch('http://localhost:3005/persons')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data:responseJson
})
})
}
render() {
return (
<div>
{
this.state.data.map( (person)=>
<PersonCard key={person.id} personProp = {person} />
)
}
</div>
)
}
}
export default SearchResults;
The logger in the constructor shows the person objects and their properties correctly, so it's there as it should be.
BUT the props value (this.props.firstName) doesn't show in the render-method, since they get rendered as "undefined" on the view. Why?

You don't define a prop called firstName here:
<PersonCard key={person.id} personProp = {person} />
Maybe you meant to access it through this.props.personProp.firstname?

In your code you are pass "key" and "personProp" props to "PersonCard" components. So inside the render function of "PersonCard" component you can access these props by "this.pops.key" and "this.props.personProp".
So if your personProp contain's the firstName then you will be able to access it by "this.prps.personProp.firstName". So you should try below code
class PersonCard extends Component {
constructor(props) {
super(props);
console.log(JSON.stringify(props));
this.state = props;
}
render() {
return (
<div>
<MuiThemeProvider muiTheme={Mui} >
<Card>
<CardHeader
title={this.props.personProp.firstName}
/>
</Card>
</MuiThemeProvider>
</div>
);
}
}
export default PersonCard;

Related

Pass input data from child to parent React.js

This may seem kind of basic but I'm just learning how to use React. Currently what I have going is when I type in the input field and submit, the system console logs my 'search' input. What I'm trying to do is pass my 'search' data from my child component to the parent. Looking for any tips or leads to the right direction.
This is what I have for my child component:
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
onChange = event => {
this.setState({ search: event.target.value });
};
onSubmit = event => {
const { search } = this.state;
event.preventDefault();
console.log(search);
};
render() {
return (
<div className='search-bar'>
<form onSubmit={this.onSubmit}>
<input
className='search'
type='text'
placeholder='Search'
onChange={this.onChange}
search={this.props.search}
value={this.state.searchinput}
parentCallback={this.onChange}
></input>
</form>
<FontAwesomeIcon className='search-icon' icon={faSearch} />
</div>
);
}
}
And in my Parent component (nothing much at the moment)
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
searchUpdate = search => {
console.log(search);
};
render() {
console.log(this.props.search);
return (
<div className='container'>
<SearchBar/>
</div>
);
}
}
Generally to pass data from child component to Parent Component, you can pass a reference of a function as props to child component from parent component and call that passed function from child component with data.
You can do something like this:
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
onChange = event => {
this.setState({ search: event.target.value });
};
onSubmit = event => {
const { search } = this.state;
event.preventDefault();
console.log(search);
this.props.passSearchData(search);
};
render() {
return (
<div className='search-bar'>
<form onSubmit={this.onSubmit}>
<input
className='search'
type='text'
placeholder='Search'
onChange={this.onChange}
search={this.props.search}
value={this.state.searchinput}
parentCallback={this.onChange}
></input>
</form>
<FontAwesomeIcon className='search-icon' icon={faSearch} />
</div>
);
}
In parent component:
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
searchUpdate = search => {
console.log(search);
this.setState({ ...state, search: search })
};
render() {
console.log(this.props.search);
return (
<div className='container'>
<SearchBar passSearchData={this.searchUpdate} />
</div>
);
}
The simplest way would be to pass a function from parent to child:
// in parent component
const setSearchValue = (search) => {
// setState to search
this.setState({search});
}
render (){
return <>
<SearchBar onsearch={this.setSearchValue} />
</>
}
// in child component
// change your searchUpdate
searchUpdate = () => {
const {onsearch} = this.state;
// function call to pass data to parent
this.props.onsearch(onsearch)
}
Just have a function that is passed as a prop to the child component. Let child component do the handle change part and pass the value back to the parent and then do whatever you want to with the value
Code sandbox: https://codesandbox.io/s/react-basic-example-vj3vl
Parent
import React from "react";
import Search from "./Search";
export default class Parent extends React.Component {
searchUpdate = search => {
console.log("in parent", search);
};
render() {
console.log(this.props.search);
return (
<div className="container">
<Search handleSearch={this.searchUpdate} />
</div>
);
}
}
Child
import React from "react";
export default class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ""
};
}
onChange = event => {
this.setState({ search: event.target.value }, () => {
console.log("in child", this.state.search);
this.props.handleSearch(this.state.search);
});
};
onSubmit = event => {
const { search } = this.state;
event.preventDefault();
console.log(search);
};
render() {
return (
<div className="search-bar">
<form onSubmit={this.onSubmit}>
<input
className="search"
type="text"
placeholder="Search"
onChange={this.onChange}
search={this.props.search}
value={this.state.searchinput}
/>
</form>
</div>
);
}
}

How can I make a list of integers click on element with corresponding id?

I have a list of ids (integer) and I have multiple components.
After a request to my API, the component receives a list of ids that should already be active.
I want to simulate a click on each element with the same id as the one in my array. I know I can use refs to do that, but I don't undertstand how to make it works with a list of elements.
Here's my code :
import React, { Component } from 'react'
import InterestBox from './InterestBox'
import Axios from 'axios'
export class InterestList extends Component {
constructor(props) {
super(props);
this.state = {pinterests: []}
}
componentDidMount() {
Axios.get('http://localhost:8000/api/interests')
.then((success) => {
this.setState({pinterests: success.data.data.interests});
})
}
componentDidUpdate(prevProps) {
console.log(JSON.stringify(prevProps));
console.log(JSON.stringify(this.props))
if(this.props.alreadyChecked != prevProps.alreadyChecked) {
this.props.alreadyChecked.forEach((item) => {
console.log(item)
})
}
}
render() {
return (
<React.Fragment>
{Object.keys(this.state.pinterests).map((interest) => {
var pinterest = this.state.pinterests[interest];
return <InterestBox id={pinterest.id} onClick={this.props.onClick} icon={pinterest.picture_src} title={pinterest.name} />
})}
</React.Fragment>
)
}
}
export default InterestList
import React, { Component } from 'react'
export class InterestBox extends Component {
constructor(props) {
super(props);
this.images = require('../../img/interests/*.svg');
this.state = {activated: false};
this.interest_box_content = React.createRef();
this.interest_text = React.createRef();
this.handleClick = this.handleClick.bind(this);
this.updateDimensions = this.updateDimensions.bind(this);
}
handleClick() {
this.props.handleClick(this.props.id, this.props.title);
this.setState(prevState => ({
activated: !prevState.activated
}))
}
updateDimensions() {
console.log((window.getComputedStyle(this.refs.interest_box_content).width))
this.refs.interest_text = (window.getComputedStyle(this.refs.interest_box_content).width)
}
render() {
return (
<div className="column is-one-fifth-desktop is-half-touch">
<div className="interest-box">
<div className="interest-box-adjuster">
<div ref={"interest_box_content"} className={"interest-box-content " + (this.state.activated == true ? 'interest-box-activated' : '')} onClick={this.handleClick}>
<img className="interest-icon" src={this.images[this.props.icon]} style={{'height': '50%'}}></img>
<i className="activated-icon fas fa-check"></i>
<span ref={"interest_text"} className="interest-text">{this.props.title}</span>
</div>
</div>
</div>
</div>
)
}
}
export default InterestBox
In the InterestList "componentDidUpdate" method, the value of the item is an integer.
I want to use this integer to "click" on the InterestBox with the corresponding "id".
How can I achieve this ?
You can store an array of elements in one ref, like this:
constructor(props) {
super(props);
this.state = {pinterests: []}
this.pinterestRefs = React.createRef()
}
...
render() {
return (
<React.Fragment>
{Object.keys(this.state.pinterests).map((interest) => {
var pinterest = this.state.pinterests[interest];
return <InterestBox id={pinterest.id} onClick={this.props.onClick} icon={pinterest.picture_src} title={pinterest.name} ref={pinterestRef => this.refs.pinterestRefs.push(pinterestRef)} />
})}
</React.Fragment>
)
}
and then call the click function on each in a componentDidMount function:
componentDidMount() {
if (this.refs.pinterestRefs.length) {
this.refs.pinterestRefs.forEach(pinterestEl => {
pinterestEl.click();
});
}
}
Since this.pinterestRefs is a ref and not an array, the push method is not available. Unfortunately, we do not have a definite length so we can't declare the refs preemptively. However, we can add it to this.refs object and the convert it to an array:
export class InterestList extends Component {
constructor(props) {
super(props);
this.state = {pinterests: []}
}
componentDidMount() {
Axios.get('http://localhost:8000/api/interests')
.then((success) => {
this.setState({pinterests: success.data.data.interests});
})
}
componentDidUpdate(prevProps) {
console.log(Object.values(this.refs)); // Array with all refs
console.log(JSON.stringify(prevProps));
console.log(JSON.stringify(this.props))
if(this.props.alreadyChecked != prevProps.alreadyChecked) {
this.props.alreadyChecked.forEach((item) => {
console.log(item)
})
}
}
render() {
return (
{/*I'm assuming each item has a unique id, if not, create one*/}
<React.Fragment>
{Object.keys(this.state.pinterests).map((interest) => {
var pinterest = this.state.pinterests[interest];
return <InterestBox id={pinterest.id} onClick={this.props.onClick} ref={pinterest.id} icon={pinterest.picture_src} title={pinterest.name} />
})}
</React.Fragment>
)
}
}
export default InterestList;

React: Remove current instance of component [duplicate]

I have have code that creates <li> elements. I need to delete elements one by one by clicking. For each element I have Delete button. I understand that I need some function to delete items by id. How to do this function to delete elements in ReactJS?
My code:
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {items: [], text: ''};
}
render() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<input onChange={this.handleChange} value={this.state.text} />
<button>{'Add #' + (this.state.items.length + 1)}</button>
</form>
</div>
);
}
handleChange(e) {
this.setState({text: e.target.value});
}
handleSubmit(e) {
e.preventDefault();
var newItem = {
text: this.props.w +''+this.props.t,
id: Date.now()
};
this.setState((prevState) => ({
items: prevState.items.concat(newItem),
text: ''
}));
}
delete(id){ // How that function knows id of item that need to delete and how to delete item?
this.setState(this.item.id)
}
}
class TodoList extends React.Component {
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}<button onClick={this.delete.bind(this)}>Delete</button></li>
))}
</ul>
);
}
}
You are managing the data in Parent component and rendering the UI in Child component, so to delete item from child component you need to pass a function along with data, call that function from child and pass any unique identifier of list item, inside parent component delete the item using that unique identifier.
Step1: Pass a function from parent component along with data, like this:
<TodoList items={this.state.items} _handleDelete={this.delete.bind(this)}/>
Step2: Define delete function in parent component like this:
delete(id){
this.setState(prevState => ({
data: prevState.data.filter(el => el != id )
}));
}
Step3: Call that function from child component using this.props._handleDelete():
class TodoList extends React.Component {
_handleDelete(id){
this.props._handleDelete(id);
}
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}<button onClick={this._handleDelete.bind(this, item.id)}>Delete</button></li>
))}
</ul>
);
}
}
Check this working example:
class App extends React.Component{
constructor(){
super();
this.state = {
data: [1,2,3,4,5]
}
this.delete = this.delete.bind(this);
}
delete(id){
this.setState(prevState => ({
data: prevState.data.filter(el => el != id )
}));
}
render(){
return(
<Child delete={this.delete} data={this.state.data}/>
);
}
}
class Child extends React.Component{
delete(id){
this.props.delete(id);
}
render(){
return(
<div>
{
this.props.data.map(el=>
<p onClick={this.delete.bind(this, el)}>{el}</p>
)
}
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<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='app'/>

calling grandparent method from grandchild functional component in react

I'm trying to call a simple method from the grandparent component in my child component but from some reason I can't , I tried every possible way but I think I'm missing something
here's the full code :
import React, { Component } from 'react';
import './App.css';
var todos = [
{
title: "Example2",
completed: true
}
]
const TodoItem = (props) => {
return (
<li
className={props.completed ? "completed" : "uncompleted"}
key={props.index} onClick={props.handleChangeStatus}
>
{props.title}
</li>
);
}
class TodoList extends Component {
constructor(props) {
super(props);
}
render () {
return (
<ul>
{this.props.todosItems.map((item , index) => (
<TodoItem key={index} {...item} {...this.props} handleChangeStatus={this.props.handleChangeStatus} />
))}
</ul>
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
todos ,
text :""
}
this.handleTextChange = this.handleTextChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeStatus = this.handleChangeStatus(this);
}
handleTextChange(e) {
this.setState({
text: e.target.value
});
}
handleChangeStatus(){
console.log("hello");
}
handleSubmit(e) {
e.preventDefault();
const newItem = {
title : this.state.text ,
completed : false
}
this.setState((prevState) => ({
todos : prevState.todos.concat(newItem),
text : ""
}))
}
render() {
return (
<div className="App">
<h1>Todos </h1>
<div>
<form onSubmit={this.handleSubmit}>
< input type="text" onChange={this.handleTextChange} value={this.state.text}/>
</form>
</div>
<div>
<TodoList handleChangeStatus={this.handleChangeStatus} todosItems={this.state.todos} />
</div>
<button type="button">asdsadas</button>
</div>
);
}
}
export default App;
The method im trying to use is handleChangeStatus() from the App component in the TodoItem component
Thank you all for your help
This line is wrong:
this.handleChangeStatus = this.handleChangeStatus(this);
//Change to this and it works
this.handleChangeStatus = this.handleChangeStatus.bind(this);

React - How to pass props to a component passed as prop

I have a React component (React v15.5.4) that you can pass other components to:
class CustomForm extends React.Component {
...
render() {
return (
<div>
{this.props.component}
</div>
);
}
}
And I have a different component that uses it:
class SomeContainer extends React.Component {
...
render() {
let someObjectVariable = {someProperty: 'someValue'};
return (
<CustomForm
component={<SomeInnerComponent someProp={'someInnerComponentOwnProp'}/>}
object={someObjectVariable}
/>
);
}
}
Everything renders fine, but I want to pass someObjectVariable prop to the child component inside CustomForm (in this case that'll be SomeInnerComponent), since in the actual code you can pass several components to it instead of just one like the example.
Mind you, I also need to pass SomeInnerComponent its own props.
Is there a way to do that?
You can achieve that by using React.cloneElement.
Like this:
class CustomForm extends React.Component {
...
render() {
return (
<div>
{React.cloneElement(this.props.component,{ customProps: this.props.object })}
</div>
);
}
}
Working Code:
class Parent extends React.Component{
render() {
return(
<Child a={1} comp={<GChild/>} />
)
}
}
class Child extends React.Component{
constructor(){
super();
this.state = {b: 1};
this.updateB = this.updateB.bind(this);
}
updateB(){
this.setState(prevState => ({b: prevState.b+1}))
}
render(){
var Comp = this.props.comp;
return (
<div>
{React.cloneElement(Comp, {b: this.state.b})}
<button onClick={this.updateB}>Click to update b</button>
</div>
);
}
}
const GChild = props => <div>{JSON.stringify(props)}</div>;
ReactDOM.render(
<Parent />,
document.getElementById('container')
);
<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='container' />
You can do in the same as you did for SomeInnerComponent.
Just pass named props.
Inside CustomForm,
render() {
const MyComponent = this.props.component; //stored it in some variable
return (
<div>
<MyComponent customProps = {this.props.object} /> //access object here and passed it or passed individual props
</div>
);
}
EDIT :
Please find the working demo here.
You have a couple of options to achieve what your asking.
class SomeContainer extends React.Component {
...
render() {
let someObjectVariable = {someProperty: 'someValue'};
return (
<CustomForm
component={<SomeInnerComponent propFromParent={someObjectVariable}/>}
object={someObjectVariable}
/>
);
}
}
Or you can clone the component prop and apply the new props as Mayank said. In your case
class CustomForm extends React.Component {
...
render() {
return (
<div>
{React.cloneElement(this.props.component,
{propFromParent:this.props.someObjectVariable})}
</div>
);
}
}
You can use react-overrides for this.
Create CustomForm:
import o from "react-overrides";
const InnerComponent = () => null; // default
class CustomForm extends React.Component {
...
render() {
return (
<div>
<InnerComponent {...o} />
</div>
);
}
}
Pass props and component of InnerComponent at overrides prop:
class SomeContainer extends React.Component {
...
render() {
let someObjectVariable = {someProperty: 'someValue'};
return (
<CustomForm
object={someObjectVariable}
overrides={{
InnerComponent: {
component: SomeInnerComponent,
props: {
someProp: 'someInnerComponentOwnProp'
}
}
}}
/>
);
}
}
<TextField place={"India"}> </TextField>
and in your component TextField
class TextField extends Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<input />
<button> {this.props.place} </button>
</div>
)
}
}
i think what you are trying to achieve is something like this you have to pass your InnerComponent as an arrow function () => ..
class SomeContainer extends React.Component { ... render() {
let someObjectVariable = {someProperty: 'someValue'};
return (
<CustomForm
component={() => <SomeInnerComponent someProp={'someInnerComponentOwnProp'}/>}
object={someObjectVariable}
/>
); } }

Categories

Resources