Utilize React.js to showcase a component featuring an onClick event handler

Just starting out with React, I'm working on a basic React application that showcases all the countries in the world on the screen along with a small search bar to display data for the searched country.

Click here to see a screenshot of the site

I'm facing an issue where I can't figure out how to display the selected country when clicked in the scrollbar.

Below is the code snippet from app.js:

import React, { Component } from 'react';
import './App.css';
import NavBar from '../Components/NavBar';
import SideBar from './SideBar';
import CountryList from '../Components/SideBarComponents/CountryList';
import Scroll from '../Components/SideBarComponents/Scroll';
import Main from './Main';
import SearchCountry from '../Components/MainComponents/SearchCountry';
import SearchedCountry from '../Components/MainComponents/SearchedCountry';
import Datas from '../Components/MainComponents/Datas';

class App extends Component {

  constructor() {
    super();
    this.state = {
      nations: [],
      searchField: '',
      button: false
    }
  }

  onSearchChange = (event) => {
    this.setState({searchField: event.target.value});
    console.log(this.state.searchField)
  }

  onClickChange = () => {
    this.setState(prevState => ({
      button: true
    }))
  }

  render() {

    const {nations, searchField, button, searchMemory} = this.state;

    const searchedNation = nations.filter(nation => {
      if(button) {
        return nation.name.toLowerCase().includes(searchField.toLowerCase())
      }
    });

    return (
      <div>
        <div>
          <NavBar/>
        </div>
          <Main>
            <div className='backgr-img'>
              <SearchCountry searchChange={this.onSearchChange} clickChange={this.onClickChange}/>
              <SearchedCountry nations={searchedNation}/>
            </div>
             <Datas nations={searchedNation}/>
          </Main>
          <SideBar>
            <Scroll className='scroll'>
              <CountryList nations={nations} clickFunc/>
            </Scroll>
          </SideBar>
      </div>
    );
  }

  componentDidMount() {
     fetch('https://restcountries.eu/rest/v2/all')
    .then(response => response.json())
    .then(x => this.setState({nations: x}));
  }

  componentDidUpdate() {
    this.state.button = false;
  }

}

export default App;

The countryList component:

import React from 'react';
import Images from './Images';

const CountryList = ({nations, clickFunc}) => {
    return (
        <div className='container' style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(115px, 3fr)'}}>
            {
                nations.map((country, i) => {
                    return (
                        <Images 
                        key={country.numericCode}
                        name={country.name}
                        flag={country.flag}
                        clickChange={clickFunc}
                        />
                    );
                })
            }
        </div>
    )                   
}
export default CountryList;

And here's the images.js file:

import React from 'react';
import './images.css'

const Images = ({name, capital, region, population, flag, numericCode, clickChange}) => {
    return (
        <div className='hover bg-navy pa2 ma1 tc w10' onClick={clickChange = () => name}>
            <img alt='flag' src={flag} />
            <div>
                <h6 className='ma0 white'>{name}</h6>
                {capital}
                {region}
                {population}
                {numericCode}
            </div>
        </div>
    );
}

export default Images;

I was thinking of using the onClick event on the individual country to retrieve and display the name of the selected country. Then, I would update the searchField with the name and set the button state to true to trigger the searchedNation function. Thanks in advance to anyone who can help me with this!

Answer №1

If you want to maintain the current structure, consider using onClickChange in Images:

onClickChange = (newName = null) => {
  if(newName) {
    this.setState(prevsState => ({
      searchField: newName
    }))
  }
  // old code continues
  this.setState(prevsState => ({
    button: true
  }))

}

Then, in the onClick event of Images, you can call:

onClick={() => {clickChange(name)}}

Alternatively, you could also explore using react hooks (although this would involve some restructuring) since you will need to modify a property from a parent component. Using the useState hook allows you to alter the value from the parent component (from Images to App):

const [searchField, setSearchField] = useState('');

Pass setSearchField as props to Images and update the searchField value when Images is clicked:

onClick={() => {
    clickChange()
    setSearchField(name)
}}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Cannot use MaterialUI Textfield/Input on iPhone devices

Recently, I encountered an issue with iPhone users being unable to type in Textfield or Input components in apps developed using MaterialUI, even when the value and setValue were properly configured. To solve this problem for each component individually, ...

Is it possible for an AngularJS controller to connect a scope variable within it to an HTML file, and then utilize the variable to display content in the HTML file?

When exploring directives, I came across examples of rendering an entire HTML file within the directive. There are also instances where controllers render HTML snippets as scope variables, enclosed in single quotation marks - like $scope.items = '&l ...

Exploring the different color variations of React Material-UI primary and secondary colors: A guide

The React Material-UI documentation mentions that it will automatically calculate light and dark variants of your primary and secondary colors. (From the documentation: https://material-ui.com/customization/palette/) const theme = createMuiTheme({ pal ...

Save the input from an HTML text area tag as a Word or PDF file using C# code

In the midst of a challenging ASP .NET project, there is a need to download the content of a text area as a file in formats like .doc, .pdf, and .txt. While it's common knowledge that plain text can be downloaded as .txt using JavaScript, the real qu ...

Are Firefox and Internet Explorer experiencing issues with CSS rendering accurately?

Experiencing some problems with IE and Firefox CSS To see the issue, visit Check it out in Chrome - it's displaying correctly there But when you view it in IE or Firefox, it's acting strange. Am I making a mistake somewhere? Any help would b ...

Modify section background color for every iteration in an image carousel

Is it possible to dynamically change the background color of the cd-hero section each time a new image is loaded in a simple slider on the home page? Can this be achieved by storing predefined colors in an array so that different images trigger different b ...

Position DIVs next to each other

After scouring through countless Stack Overflow threads in search of a solution to my issue, I still can't seem to get it right. Everyone suggests using float: left, float:right, overflow: hidden, display: block, etc., but none of them are working for ...

Using Redux to access the value of a TextInput in a React Native application

Recently, I have started delving into Redux after using vanilla React Native for quite some time. While experimenting with storing a TextInput's value, I encountered an issue where the todoInput.value remained undefined despite my efforts. Even direct ...

Is there a way to transfer innerHTML to an onClick function in Typescript?

My goal is to pass the content of the Square element as innerHTML to the onClick function. I've attempted passing just i, but it always ends up being 100. Is there a way to only pass i when it matches the value going into the Square, or can the innerH ...

Exploring ways to find a particular value within an array of objects

Struggling to make my code render the data upon searching for a specific value. I attempted using a for loop, but I keep encountering an 'unexpected token' error. Is there a more effective way to accomplish this task? While this may seem like a s ...

When submitting a form in HTML, ensure that the input checkbox returns 'On' instead of 'True'

My MVC3 app is using Project Awesome from http://awesome.codeplex.com/, but I'm encountering a strange issue with checkboxes. Inside a Modal popup, I have the following simple Html code: <input type="checkbox" class="check-box" name="IsDeleted"> ...

Axios encounters difficulty retrieving the response data following a POST request

When using axios to post data and fetch a response, I am encountering an issue where the data is successfully posted but the response data cannot be printed. This works correctly in Postman, so I'm not sure if the problem lies with the backend or fron ...

Incorporating react-css-modules in conjunction with an iframe element

While creating a component with iframes (for example, using https://github.com/ryanseddon/react-frame-component), how can you incorporate global styles into the iframe when utilizing react-css-modules? ...

Leverage arrays within a personalized filtering system

I have created an array with the structure shown below... $scope.myArr = [arg1, arg2]; Now, I am interested in developing a custom filter that will accept this array as input and compare it to another array. For instance, I intend to use it in the follow ...

What steps can I take to prevent constantly re-fetching a disabled CSS file?

I'm currently in the process of implementing a dark theme on my website, and my current method involves using 2 style sheets: <link rel="stylesheet" type="text/css" href="/flatly.css"> <link rel="stylesheet& ...

Here's a unique version: "Utilizing the onChange event of a MaterialUI Select type TextField to invoke a function."

I am currently working on creating a Select type JTextField using the MaterialUI package. I want to make sure that when the onChange event is triggered, it calls a specific function. To achieve this, I have developed a component called Select, which is es ...

Picture appears to be off-center

I created a loginPage.php file with the following content: <?php //some php stuff ?> <!DOCTYPE html> <html> <head> <title>Login Form Design</title> <link rel="stylesheet" type="text/css" href="stylelogin.c ...

Issue with nested routes in React Router v6 - seeking assistance to resolve

I have set up the following routes in my index: <BrowserRouter> <Routes> <Route path="/" element={<App />} /> <Route path="admin" element={<AdminDashboard /> } /> ...

What are the implications of incorporating listeners in redux action creators?

While developing my app, I have a feature that involves constantly monitoring location changes and updating the store accordingly. One question that has arisen is whether it would be beneficial to keep the listeners inside the action creator rather than th ...

Find the correct file path for input using JavaScript or Angular 2

How can I retrieve the full file path of a selected Excel file using either pure JavaScript or Angular 2? I am looking to have the user select an Excel file, which will then be sent to a C# WEB API controller for further processing. Currently, my setup is ...