Rendering child component and passing all options. The parent component works with the same options. Code sample of the scenario is below the options in the child component are passed from parent component as props
Parent Component
class OptionList extends Component {
renderUsers() {
if(this.props.users.length){
return this.props.users.map(option => (
<Option options={this.props.options}
/>
));
}
}
renderOptionsForm() {
return (
<div>
<form>
<div className="form-row">
<Select
options={this.props.options}
isMulti
/>
</div>
<ul>
{this.renderUsers()}
</ul>
);
}
render() {
return (
<div className="width-narrow">
{this.renderOptionsForm()}
</div>
);
}
}
// props
OptionList.propTypes = {
options: PropTypes.array.isRequired,
};
OptionList.childContextTypes = {
muiTheme: PropTypes.object.isRequired,
};
// container
export default withTracker(() => {
Meteor.subscribe('options');
Meteor.subscribe('users');
return {
options: Options.find({}).fetch().map(({ name: label, _id: value }) => ({ label, value })),
users: Users.find().fetch()
};
})(OptionList);
child component
export default class Option extends Component {
renderEditOptions() {
return (
<div>
<Select
options={this.props.options}
isMulti
/>
</div>
);
}
render() {
return (
<div>
{ this.renderEditOptions() }
</div>
);
}
}
here the values are showing correctly but the options dropdown never popups
You are using the wrong prop inside your Option component.
The prop you are using (deliveryTypes) is not being given to the component. But the Option component gets an options prop which I assume is the prop you want to use.
export default class Option extends Component {
renderEditOptions() {
return (
<div>
<Select
options={this.props.options} // <-- instead of deliveryTypes
isMulti
/>
</div>
);
}
render() {
return (
<div>
{ this.renderEditOptions() }
</div>
);
}
}
Related
Good day. I'm building a tree of components and want to use functions of root component in other components of tree. I throw function reference through all tree.
Also I use the object if me need get value from the function in not root componet.
Can you help me?
Can you show me how to do this as HOC ?
If it will be not so hard for you show examples on my code.
import React from 'react';
class Page extends React.Component{
Answer = {
value : ''
}
doSomething(){
console.log(this.Answer.value);
console.log('Ready!');
}
render(){
return(
<div>
<div>
<Body
ParentFunc={()=>this.doSomething()}
ParentParameters={this.Answer}
/>
</div>
</div>
)
}
}
export default Page
class Body extends React.Component{
render(){
const{
ParentFunc,
ParentParameters
} = this.props
return(
<div>
<div>
<SomeComponent
ParentFunc={()=>ParentFunc()}
ParentParameters={ParentParameters}
/>
</div>
</div>
)
}
}
class SomeComponent extends React.Component{
getAnswer(){
const{
ParentFunc,
ParentParameters
} = this.props
ParentParameters.value = 'Some text'
ParentFunc()
}
render(){
return(
<div onClick={()=>this.getAnswer()}>
We can?
</div>
)
}
}
I don't believe a Higher Order Component alone will solve your basic issue of prop drilling. A React Context would be a better fit for providing values and functions generally to "want to use functions of root component in other components of tree".
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
In a typical React application, data is passed top-down (parent to
child) via props, but such usage can be cumbersome for certain types
of props (e.g. locale preference, UI theme) that are required by many
components within an application. Context provides a way to share
values like these between components without having to explicitly pass
a prop through every level of the tree.
Start by creating your Context and Provider component:
const QnAContext = React.createContext({
answer: {
value: ""
},
doSomething: () => {}
});
const QnAProvider = ({ children }) => {
const answer = {
value: ""
};
const doSomething = () => {
console.log(answer.value);
console.log("Ready!");
};
return (
<QnAContext.Provider value={{ answer, doSomething }}>
{children}
</QnAContext.Provider>
);
};
Render QnAProvider in your app somewhere wrapping the React subtree you want to have access to the values being provided:
<QnAProvider>
<Page />
</QnAProvider>
Consuming the Context:
Class-based components consume contexts via the render props pattern.
<QnAContext.Consumer>
{({ answer, doSomething }) => (
<SomeComponent doSomething={doSomething} answer={answer}>
We can?
</SomeComponent>
)}
</QnAContext.Consumer>
Functional components can use the useContext React hook
const SomeComponent = ({ children }) => {
const { answer, doSomething } = useContext(QnAContext);
getAnswer = () => {
answer.value = "Some text";
doSomething();
};
return <div onClick={this.getAnswer}>{children}</div>;
};
Here is where using a Higher Order Component may become useful. You can abstract the QnAContext.Consumer render props pattern into a HOC:
const withQnAContext = (Component) => (props) => (
<QnAContext.Consumer>
{(value) => <Component {...props} {...value} />}
</QnAContext.Consumer>
);
Then you can decorate components you want to have the context values injected into.
const DecoratedSomeComponent = withQnAContext(SomeComponent);
...
<DecoratedSomeComponent>We can with HOC?</DecoratedSomeComponent>
Note: The point of doing all this was to move the values and functions that were previously defined in Page into the Context, so they are no longer passed from Page though Body to SomeComponent (or any other children components).
Demo
Sandbox Code:
const QnAContext = React.createContext({
answer: {
value: ""
},
doSomething: () => {}
});
const QnAProvider = ({ children }) => {
const answer = {
value: ""
};
const doSomething = () => {
console.log(answer.value);
console.log("Ready!");
};
return (
<QnAContext.Provider value={{ answer, doSomething }}>
{children}
</QnAContext.Provider>
);
};
const withQnAContext = (Component) => (props) => (
<QnAContext.Consumer>
{(value) => <Component {...props} {...value} />}
</QnAContext.Consumer>
);
class SomeComponent extends React.Component {
getAnswer = () => {
const { doSomething, answer } = this.props;
answer.value = "Some text";
doSomething();
};
render() {
return (
<button type="button" onClick={this.getAnswer}>
{this.props.children}
</button>
);
}
}
const DecoratedSomeComponent = withQnAContext(SomeComponent);
class Body extends React.Component {
render() {
return (
<div>
<div>
<QnAContext.Consumer>
{({ answer, doSomething }) => (
<SomeComponent doSomething={doSomething} answer={answer}>
We can?
</SomeComponent>
)}
</QnAContext.Consumer>
</div>
<div>
<DecoratedSomeComponent>We can with HOC?</DecoratedSomeComponent>
</div>
</div>
);
}
}
class Page extends React.Component {
render() {
return (
<div>
<div>
<Body />
</div>
</div>
);
}
}
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<QnAProvider>
<Page />
</QnAProvider>
</div>
);
}
Based on your current code I am making the assumption that Body does not modify the values of ParentFunc and ParentParameters before passing them down to SomeComponent.
You have a hierarchy
<Page>
<Body>
<SomeComponent>
</Body>
</Page>
and you want to pass props from Page to SomeComponent without going through Body.
You can do this using children
children is a special prop representing the JSX child elements of the component. We make it so that Body renders the children that it got through props:
class Body extends React.Component{
render() {
return(
<div>
<div>
{this.props.children}
</div>
</div>
)
}
}
We set that children prop by using a <SomeComponent/> element inside of the <Body>:
render() {
return (
<div>
<div>
<Body>
<SomeComponent
ParentFunc={() => this.doSomething()}
ParentParameters={this.Answer}
/>
</Body>
</div>
</div>
);
}
Note that you cannot directly modify the value that you got from the parent, which is what you were doing with ParentParameters.value = 'Some text'. If you want to update the state of the parent then you need to do that through your callback function props. So your code should look something like this:
import React from "react";
class Body extends React.Component {
render() {
return (
<div>
<div>{this.props.children}</div>
</div>
);
}
}
class SomeComponent extends React.Component {
state = {
showAnswer: false
};
onClick() {
// update answer in parent
this.props.setAnswer("Some text");
// change state to reveal answer
this.setState({ showAnswer: true });
}
render() {
return (
<div>
{this.state.showAnswer && <div>Answer is: {this.props.answer}</div>}
<div onClick={() => this.onClick()}>We can?</div>
</div>
);
}
}
class Page extends React.Component {
state = {
value: ""
};
render() {
return (
<div>
<div>
<Body>
<SomeComponent
answer={this.state.value}
setAnswer={(answer) => this.setState({ value: answer })}
/>
</Body>
</div>
</div>
);
}
}
export default Page;
I want to print out the list of numbers in my iteration, what am I doing wrong?
main.js component:
export class Main extends Component {
render() {
return (
<div>
<div className="wrapper">
<h1>car2go data</h1>
{Car2go.placemarks.map((content, index) => {
return <RenderTable content={content} key={index} />;
})}
</div>
</div>
);
}
}
export default Main;
renderTable.js component
import React, { Component } from "react";
export class RenderTable extends Component {
render() {
const { content } = this.props;
const { key } = this.props;
return (
<div>
<p>
<span>{key}</span>
{content.address}
</p>
</div>
);
}
}
export default RenderTable;
I'm able to print the content. address values, for each iteration, but I want to number the list, that's why I put a span before this. I can even see the key attribute printing out the number in inspector mode, but I need that in the HTML.
key in react has a special meaning and it is useful for listing and uniquely identifying the elements. Don't use key as a props unless it is used for unique listing. Ref
Try to replace this,
<RenderTable content={content} key={index} />
with this,
<RenderTable content={content} ind={index} />
and use like this,
export class RenderTable extends Component {
render() {
const { content } = this.props;
const { ind } = this.props;
return (
<div>
<p>
<span>{ind}</span>
{content.address}
</p>
</div>
);
}
}
You are trying to use the key prop in component. But that key prop is just for react's internal use. So, that key was not included in this.props by default. Hence, you need to use some other prop name (other than 'key') to pass index.
So, please change this from
<RenderTable content={content} key={index} />
to
<RenderTable content={content} key={index} num={index} />
then you can use num like
export class RenderTable extends Component {
render() {
const { content } = this.props;
const { num } = this.props;
return (
<div>
<p>
<span>{num}</span>
{content.address}
</p>
</div>
);
}
}
Hope this helps.
I need to have the user edit the url the "path" appears in the input of the other component and when searching the input change the url in real time. How can I use "withRouter" to perform this function?
// App.js component
class App extends Component {
render() {
const { match, location, history } = this.props;
return (
<div >
<Search
searchString={location.pathname}
/>
</div>
)
}
}
export default withRouter(App)
//Search.js component
const Search = ({ searchString }) => (
<div>
<input
value={searchString}
type="search"
placeholder="Search"
aria-label="Search"
/>
</div>
)
This should work for you although I'm not sure redirecting user to another page while typing into search input is a good UX.
// App.js component
class App extends Component {
state = {
searchString: this.props.location.pathname
}
handleSearch = (event) => {
this.setState(
{ searchString: event.target.value },
() => this.props.history.push('/search?query=' + this.state.searchString)
);
}
render() {
return (
<div >
<Search
onChange={this.handleSearch}
searchString={this.state.searchString}
/>
</div>
)
}
}
export default withRouter(App)
const Search = ({ searchString, onChange }) => (
<div>
<input
onChange={onChange}
value={searchString}
type="search"
placeholder="Search"
aria-label="Search"
/>
</div>
)
In my app.js, I have this
render() {
return (
<div id="App">
<SearchBar />
</div>
);
}
And inside of SearchBar, I import react-autosuggest and have this -
render() {
const { value, suggestions } = this.state;
const inputProps = {
placeholder: "Search",
value,
onChange: this.onChange
};
return (
<Autosuggest
style={style}
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
onSubmit={this.doSomething}
/>
);
}
Where all these functions are standard boilerplate functions that react-autosuggest uses. How do I access what was searched for inside of SearchBar inside of it's parent, app.js?
You can use props to raise the data from the Autosuggest events to the parent component. Create a method inside App and pass it down as a prop to the SearchBar component. Then, call it with the Autosuggest event.
App
class App extends React.Component {
onSubmit(e) {
// `e` is the data that was passed through from the `Autosuggest` event.
console.log(e);
}
render() {
return (
<div id="App">
<SearchBar onSubmit={this.onSubmit} />
</div>
);
}
}
SearchBar
<Autosuggest onClick={this.props.onSubmit} />
You can use a callback function at the SearchBar component. Follow the steps below according to your use case:
Add below function at SearchBar component
onHandleChange(event, value){
this.setState({ value });
this.props.getInputData(event, value);
}
Use above function at AutoSuggest component
return (
<Autosuggest
...
onChange={(event, value) => this.onHandleChange(event, value)}
...
/>
);
Use SearchBar component like
render() {
return (
<div id="App">
<SearchBar getInputData={(event, value) => this.getAutosuggestInput(event, value)}/>
</div>
);
}
Here you get the value of input box at the parent component
getAutosuggestInput = (event, value) => {
//add your logic here
}
A beginner question: I am rendering a collection of items with React render function and I noticed that React automatically adds attribute is="null" to each rendered DOM element.
Why is React doing that? Is the key applied correctly or not? The respective code is:
export default class ItemList extends Component {
render() {
let { items } = this.props
items = items.map((item) => {
return <Item key={item.id} item={item} />
})
return (
<div>
{items}
</div>
)
}
}
export default class Item extends Component {
render() {
const { item } = this.props
return (
<div>
<h3>{item.attributes.name}</h3>
</div>
)
}
}
In the DOM, each div and h3 has attribute is="null"
<div is="null">
<h3 is="null">Item 1</h3>
</div>
This is Firefox issue and its already in pipeline
https://discuss.reactjs.org/t/is-null-attribute-on-every-tag/4032/7
https://github.com/facebook/react/pull/6896